<?php

require_once(dirname(__FILE__) . '/appconf.php');

class Product extends Site {

    function setup() {
        $this->run_modes('invite_list', 'r', 'fg', 'star', 'campaign_list', 'submitReport_list', 'submit_application', 'invite_inpage', 'invite_page', 'report_inpage', 'detail', 'reportDetail', 'readReport_list', 'report_show', 'report_add', 'ajax', 'approveReport', 'emailApplication', 'report_edit', 'clear');
        $this->start_mode('invite_list');
        $this->selfurl = '/product.php';
        $this->pagesize = 5;
        parent::setup();
        include("common.php");
    }

    function cgiapp_prerun() {
        $this->dbMove = getModel('Model_dbMove');
        $this->Product = getModel('Model_Product');
        $this->Product_application = getModel('Model_ProductApplication');
        $this->Lookup = getModel('Model_Lookup');
        $this->ProductReports = getModel('Model_ProductReports');
        $this->ProductReportsComment = getModel('Model_ProductReportsComment');
        $this->MemberLike = getModel('Model_MemberLike');
        $this->ModelMember = getModel('Model_Member');
        $this->member = $this->s_param('memberData');
        $this->email_obj = getLibClass('itrialEmail');
        $this->Campaign = getModel('Model_Campaign');
        $this->Points = getModel('Model_Points');
        $this->StaruserReport = getModel('Model_StaruserReport');
        $this->StaruserUser = getModel('Model_StaruserUser');
        $this->StaruserHiliteuser = getModel('Model_StaruserHiliteuser');
        $this->FG = getModel('Model_FG');
        parent::cgiapp_prerun();
    }

    function action_invite_list() {
        $order_q = intval($this->get_q('order', 1, 'int')); //下拉選項
        $mtype = intval($this->get_q('mtype', 1, 'int')); //邀請類型1、5
        $tmpl = $mtype == 5 ? 'p_invite_list_expert.php' : 'p_invite_list_general.php';

        $order = !empty($order_q) ? $order_q : 1;
        //邀請排序
        switch ($order) {
            case 2:
                $orderby = "TB1.apply_endtime asc,TB1.id desc";
                break;
            case 3:
                $orderby = "TB1.click desc,TB1.id desc";
                break;
            case 1:
            default:
                $orderby = "TB1.apply_endtime desc,TB1.id desc";
                break;
        }

        $kvcobj = getCache('product_invite_list', array('expire' => KVC_EXPIRE));

        //邀請列表
        $invite_list = $kvcobj->get($order . '_' . $mtype . '_invite_list');
        if (!$invite_list) {
            $product_list1 = $this->Product->getProductList($mtype, 1, $orderby, 0, 0);
            $invite_list = isset($product_list1['result']) && !empty($product_list1['result']) ? $product_list1['result'] : array();
            if ($invite_list) {
                foreach ($invite_list as $k => $v) {
                    $invite_list[$k]['_difTime'] = explode(" ", str_diff_time($v['apply_endtime']));
                    $product = $this->Product->get_product_byid($v['id']);
                    $invite_list[$k]['capacity'] = $product['capacity_trial'];
                    $invite_list[$k]['_photo_url'] = PhotoResize($v['cover'], 158, 158);
                    $tags = !empty($v['tag']) ? trim($v['tag']) : '';
                    $invite_list[$k]['tags'] = explode("|", $tags);
                    $invite_list[$k]['points'] = $product['points'];
                }
            }
            $kvcobj->set($order . '_' . $mtype . '_invite_list', $invite_list);
        }

        $invite_older_list = $kvcobj->get($order . '_' . $mtype . '_invite_older_list');
        if (!$invite_older_list) {
            // 已錯過的邀請列表
            $older_orderby = 'TB1.apply_endtime desc,TB1.id desc';
            $product_list2 = $this->Product->getProductList($mtype, 3, $older_orderby, 1, 16);
            $invite_older_list = isset($product_list2['result']) && !empty($product_list2['result']) ? $product_list2['result'] : array();
            if ($invite_older_list) {
                foreach ($invite_older_list as $k => $v) {
                    $invite_older_list[$k]['_photo_url'] = PhotoResize($v['cover'], 158, 158);
                    $invite_older_list[$k]['name'] = wordscut($v['name'], 11);
                    $invite_older_list[$k]['cname'] = wordscut($v['cname'], 9);
                }
            }
            $kvcobj->set($order . '_' . $mtype . '_invite_older_list', $invite_older_list);
        }
        //echo '<pre>'.var_export($res,1).'</pre>';
        $this->tmpl_assign('invite_list', $invite_list);
        $this->tmpl_assign('invite_older_list', $invite_older_list);
        $this->tmpl_assign('order', $order);
        $this->tmpl_assign('mtype', $mtype);
        return $this->load_tmpl($tmpl);
    }

    function action_campaign_list() {
        $id = intval($this->get_q('id', 1, 'int'));
        $kvcobj = getCache('product_campaign_list', array('expire' => KVC_EXPIRE));

        $campaign_list = $kvcobj->get($id);
        if (!$campaign_list) {
            $campaign_list = $this->Campaign->getList($id);
            if ($campaign_list) {
                foreach ($campaign_list['products'] as $k => $v) {
                    $campaign_list['products'][$k]['_difTime'] = explode(" ", str_diff_time($v['apply_endtime']));
                    $campaign_list['products'][$k]['_photo_url'] = PhotoResize($v['cover'], 158, 158);
                    $tags = !empty($v['tag']) ? trim($v['tag']) : '';
                    $campaign_list['products'][$k]['tags'] = explode("|", $tags);
                    if (strtotime($v['apply_endtime']) > time()) {
                        $campaign_list['products'][$k]['_url'] = optimize_url('product', 'invite_inpage', 'mtype=' . $v['member_type'] . '&pid=' . $v['id']);
                        $campaign_list['products'][$k]['_class'] = "btn_submit";
                    } elseif (strtotime($v['report_starttime']) < time() && strtotime($v['report_endtime']) > time()) {
                        $campaign_list['products'][$k]['_url'] = optimize_url('product', 'report_inpage', 'mtype=' . $v['member_type'] . '&pid=' . $v['id']);
                        $campaign_list['products'][$k]['_class'] = "btn_s_report";
                    } else {
                        $campaign_list['products'][$k]['_url'] = optimize_url('product', 'detail', 'mtype=' . $v['member_type'] . '&pid=' . $v['id']);
                        $campaign_list['products'][$k]['_class'] = "btn_view";
                    }
                }
                $campaign_list['photo1_image1_p'] = PhotoResize($campaign_list['photo1_image1'], 655, 150);
                $campaign_list['photo2_image1_p'] = PhotoResize($campaign_list['photo2_image1'], 308, 23);
            }
            $kvcobj->set($id, $campaign_list);
        }
        //echo '<pre>'.var_export($campaign_list,1).'</pre>';
        $this->tmpl_assign('campaign_list', $campaign_list);
        return $this->load_tmpl("p_campaign_list.php");
    }

    function action_submitReport_list() {
        $mtype = intval($this->get_q('mtype', 1, 'int')); //列表類型
        $tmpl = $mtype == 5 ? 'p_submitReport_list_expert.php' : 'p_submitReport_list_general.php';

        $kvcobj = getCache('product_submitReport_list', array('expire' => KVC_EXPIRE));
        $submitReport_list = $kvcobj->get($mtype);
        if (!$submitReport_list) {
            $orderby = 'TB1.report_starttime desc,TB1.id desc';
            $product_list = $this->Product->getProductList($mtype, 2, $orderby, 0, 0);
            $submitReport_list = isset($product_list['result']) && !empty($product_list['result']) ? $product_list['result'] : array();
            if ($submitReport_list) {
                foreach ($submitReport_list as $k => $v) {
                    $submitReport_list[$k]['name'] = wordscut($v['name'], 12);
                    $submitReport_list[$k]['cname'] = wordscut($v['cname'], 12);
                    $submitReport_list[$k]['_photo_url'] = PhotoResize($v['cover'], 116, 116);
                    $submitReport_list[$k]['_rep_count'] = $v['reports'];
                }
            }
            $kvcobj->set($mtype, $submitReport_list);
        }
        //echo '<pre>'.var_export($res,1).'</pre>';
        $this->tmpl_assign('mtype', $mtype);
        $this->tmpl_assign('result', $submitReport_list);
        return $this->load_tmpl($tmpl);
    }

    function action_submit_application() {
        $pid = intval($this->get_q('pid', 1, 'int'));
        $kvcobj = getCache('product_submit_application', array('expire' => KVC_EXPIRE));
        $kvcobj1 = getCache('get_product_info', array('expire' => KVC_EXPIRE));
        $product = $kvcobj1->get($pid);
        if (!$product) {
            $product = $this->Product->get_product_info($pid);
            $kvcobj1->set($pid, $product);
        }
        if (time() < strtotime($product['apply_starttime'])) {
            return showMsgCode('活動時間有誤！', '/');
        }
        $mtype = !empty($product['member_type']) ? $product['member_type'] : intval($this->get_q('mtype', 1, 'int'));
        $tmpl = $mtype == 5 ? 'p_submit_application_expert.php' : 'p_submit_application_general.php';

        if (empty($this->member)) {
            $toURL = optimize_url('product', 'submit_application', 'pid=' . $pid . '&mtype=' . $mtype);

            $this->s_param('toURL', $toURL);
            return showMsgCode(NO_LOGIN, '/member.php?action=login');
        }

        $member_app_count = db_query_count('product_application', "mid=" . mysql_escape_string($this->member['id']) . " and oid=" . mysql_escape_string($pid));
        if ($member_app_count > 0) {
            return showMsgCode(HAS_APPLY, '/');
        }

        if ($this->get_q('issubmit')) {
            $array = array(
                'pid' => $pid,
                'mid' => $this->member['id'],
                'reason' => htmlspecialchars($this->get_q('reason', '')),
                'reason_size' => intval($this->get_q('reason_size', 0, 'int')),
                'photo' => $this->get_q('photo_path', ''),
                'ques' => $this->get_q('ques'),
                'isread' => intval($this->get_q('isread', 0, 'int')),
                'facebook' => $this->get_q('facebook'),
            );
            $global_url = $this->param('URL');
            $iret = $this->Product->submit_application_updb($array, $product, $global_url);
            if (is_array($iret))
                $this->iframeReturn($iret[0], $iret[1], $iret[2]);
        } else {
            $this->tmpl_assign('pid', $pid);
            $this->tmpl_assign('product', $product);
            $this->tmpl_assign('mtype', $mtype);
            $this->tmpl_assign('DOMAIN', DOMAIN);
            $this->tmpl_assign('selfurl', $this->selfurl);
            $pageValue = array();
            $pageValue['title'] = !empty($product['type_name']) ? $product['type_name'] . " - " : "";
            $pageValue['title'] .=!empty($product['cname']) ? $product['cname'] . " - " : "";
            $this->tmpl_assign('pageValue', $pageValue);
            $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
            return $this->load_tmpl($tmpl);
        }
    }

    function action_invite_inpage() {
        $pid = intval($this->get_q('pid', 1, 'int'));
        $page = intval($this->get_q('page', 1, 'int'));

        db_handle('update product set click=click+1 where id=' . mysql_escape_string($pid));

        $kvcobj = getCache('product_invite_inpage', array('expire' => KVC_EXPIRE));
        $retDatas = $kvcobj->get($this->member['id'] . '_' . $pid . '_' . $page . '_0');
        if (!$retDatas) {
            $retDatas = $this->Product->invite_data($this->member['id'], $pid, $page, 0);
            $kvcobj->set($this->member['id'] . '_' . $pid . '_' . $page . '_0', $retDatas);
        }

        $this->tmpl_assign('s', $retDatas['s']);
        $this->tmpl_assign('mtype', $retDatas['mtype']);
        $this->tmpl_assign('pid', $pid);
        $this->tmpl_assign('turnpage', $retDatas['turnpage']);
        $this->tmpl_assign('pagelist', $retDatas['pagelist']);
        $this->tmpl_assign('product', $retDatas['product']);
        $this->tmpl_assign('userlist', $retDatas['userlist']);
        $this->tmpl_assign('reportlist', $retDatas['reportlist']);
        $this->tmpl_assign('NO_USERNAME', NO_USERNAME);
        $this->tmpl_assign('NO_PASSWORD', NO_PASSWORD);
        $this->tmpl_assign('ERR_CAPTCHA', ERR_CAPTCHA);
        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        $this->tmpl_assign('pageValue', $retDatas['pageValue']);
        $this->tmpl_assign('pageoptions', $retDatas['pageoptions']);
        $this->tmpl_assign('memberData', $this->member);
        $global_url = $this->param('URL');
        $this->tmpl_assign('global_url', $global_url);
        return $this->load_tmpl($retDatas['tmpl']);
    }

    function action_invite_page() {
        $pid = intval($this->get_q('pid', 0, 'int'));

        db_handle('update product set click=click+1 where id=' . mysql_escape_string($pid));

        $m = $this->get_q('m', '');
        $md5_pid = md5($pid . 'imoreHK');
        if ($m != $md5_pid) {
            return showMsgCode('鏈接有誤！', '/');
        }
        $page = intval($this->get_q('page', 1, 'int'));
        $kvcobj = getCache('product_invite_inpage', array('expire' => KVC_EXPIRE));
        $retDatas = $kvcobj->get($this->member['id'] . '_' . $pid . '_' . $page . '_1');
        if (!$retDatas) {
            $retDatas = $this->Product->invite_data($this->member['id'], $pid, $page, 1);
            $kvcobj->set($this->member['id'] . '_' . $pid . '_' . $page . '_1', $retDatas);
        }

        $this->tmpl_assign('s', $retDatas['s']);
        $this->tmpl_assign('mtype', $retDatas['mtype']);
        $this->tmpl_assign('pid', $pid);
        $this->tmpl_assign('turnpage', $retDatas['turnpage']);
        $this->tmpl_assign('pagelist', $retDatas['pagelist']);
        $this->tmpl_assign('product', $retDatas['product']);
        $this->tmpl_assign('userlist', $retDatas['userlist']);
        $this->tmpl_assign('reportlist', $retDatas['reportlist']);
        $this->tmpl_assign('NO_USERNAME', NO_USERNAME);
        $this->tmpl_assign('NO_PASSWORD', NO_PASSWORD);
        $this->tmpl_assign('ERR_CAPTCHA', ERR_CAPTCHA);
        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        $this->tmpl_assign('pageValue', $retDatas['pageValue']);
        $this->tmpl_assign('pageoptions', $retDatas['pageoptions']);
        $this->tmpl_assign('memberData', $this->member);
        $global_url = $this->param('URL');
        $this->tmpl_assign('global_url', $global_url);
        return $this->load_tmpl($retDatas['tmpl']);
    }

    function action_report_inpage() {
        $pid = intval($this->get_q('pid', 1, 'int'));
        $page = intval($this->get_q('page', 1, 'int'));
        //人氣自增1
        db_handle('update product set click=click+1 where id=' . mysql_escape_string($pid));

        $kvcobj = getCache('product_report_inpage', array('expire' => KVC_EXPIRE));
        $kvcobj1 = getCache('get_product_info', array('expire' => KVC_EXPIRE));
        $product = $kvcobj1->get($pid);
        if (!$product) {
            $product = $this->Product->get_product_info($pid);
            $kvcobj1->set($pid, $product);
        }

        if (time() < strtotime($product['apply_starttime'])) {
            return showMsgCode('活動時間有誤！', '/');
        }
        $mtype = $product['member_type'];
        $tmpl = $mtype == 5 ? 'p_report_inpage_expert.php' : 'p_report_inpage_general.php';

        $userlist1 = $kvcobj->get($pid . '_userlist1');
        if (!$userlist1) {
            $product_user_list1 = $this->Product_application->getAllUser($pid, 2);
            $userlist1 = isset($product_user_list1['result']) && !empty($product_user_list1['result']) ? $product_user_list1['result'] : array();
            if ($userlist1) {
                foreach ($userlist1 as $k => $v) {
                    $userlist1[$k]['photo_l'] = imore_avatar($v['photo']);
                }
            }
            $kvcobj->set($pid . '_userlist1', $userlist1);
        }

        $userlist2 = $kvcobj->get($pid . '_userlist2');
        if (!$userlist2) {
            $product_user_list2 = $this->Product_application->getAllUser($pid, 0);
            $userlist2 = isset($product_user_list2['result']) && !empty($product_user_list2['result']) ? $product_user_list2['result'] : array();
            if ($userlist2) {
                foreach ($userlist2 as $k => $v) {
                    $userlist2[$k]['photo_l'] = imore_avatar($v['photo']);
                }
            }
            $kvcobj->set($pid . '_userlist2', $userlist2);
        }

        $product_app_list = $kvcobj->get($pid . '_' . $page . '_product_app_list');
        if (!$product_app_list) {
            $product_app_list = $this->Product_application->getApplicationList($pid, 4, "id desc", $page, $this->pagesize);
            $kvcobj->set($pid . '_' . $page . '_product_app_list', $product_app_list);
        }
        $reportlist = isset($product_app_list['result']) && !empty($product_app_list['result']) ? $product_app_list['result'] : array();
        if ($reportlist) {
            foreach ($reportlist as $k => $v) {
                $reportlist[$k]['photo_l'] = imore_avatar($v['photo']);
            }
        }

        $pagelist = '';
        if (!empty($product_app_list) && !empty($product_app_list['pageinfo']['total'])) {
            $pagelist = showPage($product_app_list['pageinfo']['total'], $this->pagesize, $page, optimize_url('product', 'report_inpage', 'mtype=' . $mtype . '&pid=' . $pid));
        }

        //是否隱藏已申請會員及三部曲部份
        $turnpage = $page > 1 ? 1 : 0;

        if (!empty($this->member['id'])) {
            $_mem = $this->ModelMember->getMemberCondition($this->member['id']);
            $_member_arr = array();
            if ($_mem['result'])
                $_member_arr = $_mem['result'][0];
            if (!empty($_member_arr['address']) && !empty($_member_arr['homepage'])) {
                $s = 1;
            } else {
                $s = 0;
            }
        } else {
            $s = 0;
        }

        $this->tmpl_assign('s', $s);
        $this->tmpl_assign('pid', $pid);
        $this->tmpl_assign('mtype', $mtype);
        $this->tmpl_assign('turnpage', $turnpage);
        $this->tmpl_assign('pagelist', $pagelist);
        $this->tmpl_assign('selfurl', $this->selfurl);
        $this->tmpl_assign('product', $product);
        $this->tmpl_assign('userlist1', $userlist1);
        $this->tmpl_assign('userlist2', $userlist2);
        $this->tmpl_assign('reportlist', $reportlist);
        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        $pageValue = array();
        $pageValue['title'] = !empty($product['type_name']) ? $product['type_name'] . " - " : "";
        $pageValue['title'] .=!empty($product['cname']) ? $product['cname'] . " - " : "";
        $this->tmpl_assign('pageValue', $pageValue);
        $pageoptions = array();
        $pageoptions['csses'][0] = "jquery.lightbox-0.5";
        $pageoptions['jses'][0] = "jquery.lightbox-0.5.min";
        $this->tmpl_assign('pageoptions', $pageoptions);
        $this->tmpl_assign('memberData', $this->member);
        $global_url = $this->param('URL');
        $this->tmpl_assign('global_url', $global_url);
        return $this->load_tmpl($tmpl);
    }

    function action_r() {
        $pid = intval($this->get_q('pid', 1, 'int'));
        $kvcobj1 = getCache('get_product_byid', array('expire' => KVC_EXPIRE));
        $product = $kvcobj1->get($pid);
        if (!$product) {
            $product = $this->Product->get_product_byid($pid);
            $kvcobj1->set($pid, $product);
        }
        $this->redirect(optimize_url("product", "detail", "mtype=" . $product['member_type'] . "&pid=" . $pid));
    }

    function action_detail() {
        $pid = intval($this->get_q('pid', 1, 'int'));
        $_page = intval($this->get_q('page', 1, 'int'));

        //人氣自增1
        db_handle('update product set click=click+1 where id=' . mysql_escape_string($pid));

        $kvcobj = getCache('product_detail', array('expire' => KVC_EXPIRE));
        $kvcobj1 = getCache('get_product_byid', array('expire' => KVC_EXPIRE));
        $product = $kvcobj1->get($pid);
        if (!$product) {
            $product = $this->Product->get_product_byid($pid);
            $kvcobj1->set($pid, $product);
        }

        $t = intval($this->get_q('t', 0, 'int'));

        if (empty($product))
            return showMsgCode('記錄不存在或已經刪除！', '/');

        if (time() < strtotime($product['apply_starttime'])) {
            return showMsgCode('活動時間有誤！', '/');
        }


        $mtype = $product['member_type'];
        $tmpl = $mtype == 5 ? 'p_detail_expert.php' : 'p_detail_general.php';

        $product['is_report_add'] = time() <= strtotime($product['report_starttime']) ? 0 : 1;

        //體驗天數
        $product['_diff_day'] = ceil((strtotime($product['report_endtime']) - strtotime($product['report_starttime'])) / 86400);

        //圖片url
        $product['_photo_url'] = PhotoResize($product['cover'], 158, 158);
        //評分
        /*
          if(!empty($product['product_reports_stat']['category_score_num'])){
          $product['_overall'] = round($product['product_reports_stat']['good']/$product['product_reports_stat']['category_score_num']*100);
          }else{

          }
         */
        $product['_overall'] = !empty($product['product_reports_stat']['scores']) ? $product['product_reports_stat']['scores'] : 0;
        //right 產品屬性info

        if (!empty($product['price'])) {
            $product['_attr']['價格'] = '$' . $product['price'];
        }
        if (!empty($product['attribute_value1'])) {
            $product['_attr']['實際容量'] = nl2br($product['attribute_value1']);
        }

        for ($i = 2; $i < 9; $i++) {
            if (!empty($product['attribute_value' . $i])) {
                $product['_attr'][$product['attribute_label' . $i]] = nl2br($product['attribute_value' . $i]);
            }
        }
        if (!empty($product['about_url']) && !empty($product['about_txt'])) {
            $product['_attr']['相關資料'] = "<a target='_blank' href='" . $product['about_url'] . "' target>" . nl2br($product['about_txt']) . "</a>";
        }
        //if(!empty($product['body'])){ $product['_attr']['編輯短評'] = nl2br($product['body']);}
        //產品好評度 餅圖url

        $_num1 = empty($product['product_reports_stat']['well_score_num1']) ? 0 : intval($product['product_reports_stat']['well_score_num1']);
        $_num2 = empty($product['product_reports_stat']['well_score_num1']) ? 0 : intval($product['product_reports_stat']['well_score_num2']);
        $_num3 = empty($product['product_reports_stat']['well_score_num1']) ? 0 : intval($product['product_reports_stat']['well_score_num3']);
        $_num4 = empty($product['product_reports_stat']['well_score_num1']) ? 0 : intval($product['product_reports_stat']['well_score_num4']);
        $_num5 = empty($product['product_reports_stat']['well_score_num1']) ? 0 : intval($product['product_reports_stat']['well_score_num5']);
        $_img_color = $mtype == 5 ? 1 : 2;
        $pie_datas = array(
            'datas' => array($_num1, $_num2, $_num3, $_num4, $_num5),
            'colorType' => $_img_color
        );
        $product['_pie_url'] = getImgUrl($pie_datas);

        //好評度（很好、好、一般、差、很差）
        $well_list = $kvcobj->get('well_list');
        if (!$well_list) {
            $well_list = $this->Lookup->getLookup('product_reports_well');
            $kvcobj->set('well_list', $well_list);
        }
        $product['_well_score'] = $well_list['result'];
        if (!empty($product['product_reports_stat']['category_score_num']) && $product['product_reports_stat']['category_score_num'] > 0) {
            for ($i = 1; $i < 6; $i++) {
                $product['_well_score']['num' . $i] = round($product['product_reports_stat']['well_score_num' . $i] / $product['product_reports_stat']['category_score_num'] * 100) . '%';
            }
        } else {
            $product['_well_score']['num1'] = $product['_well_score']['num2'] = $product['_well_score']['num3'] = $product['_well_score']['num4'] = $product['_well_score']['num5'] = '0%';
        }

        $agegroup_list = $kvcobj->get('agegroup_list');
        if (!$agegroup_list) {
            $agegroup_list = $this->Lookup->getLookup('agegroup');
            $kvcobj->set('agegroup_list', $agegroup_list);
        }

        for ($i = 1; $i < 9; $i++) {
            if (isset($product['vote_option_data']['result'][$i - 1]) && !empty($product['vote_option_data']['result'][$i - 1])) {
                $product['_vote_opt'][$product['vote_option_data']['result'][$i - 1]['cname']] = !empty($product['product_reports_stat']['category_score' . $i]) ? round($product['product_reports_stat']['category_score' . $i] / 5 * 100) . '%' : '0%';
            }
            if (isset($agegroup_list['result'][$i - 1]) && !empty($agegroup_list['result'][$i - 1])) {
                $product['_age_group'][$agegroup_list['result'][$i - 1]['cname']] = !empty($product['product_reports_stat']['category_score_num']) && !empty($product['product_reports_stat']['agegroup' . $i]) ? round($product['product_reports_stat']['agegroup' . $i] / $product['product_reports_stat']['category_score_num'] * 100) . '%' : '0%';
            }
        }

        //獲得報告列表資料
        $tab = intval($this->get_q('tab', 1, 'int')); //改為tab位選項
        $tab = $tab == 0 ? 1 : $tab;
        $body_skin_list = $kvcobj->get('body_skin_list');
        if (!$body_skin_list) {
            $body_skin_list = $this->Lookup->getLookup('body_skin'); //膚質
            $kvcobj->set('body_skin_list', $body_skin_list);
        }
        $global_url = $this->param('URL');
        $page = $tab == 1 ? $_page : 1;
        $reports_list = $kvcobj->get('reports_list_' . $this->member['id'] . '_' . $pid . '_' . $page . '_' . $product);
        if (!$reports_list) {
            $reports_list = $this->Product->get_detail_report_list($this->member['id'], $pid, 1, $page, $product, $global_url);
            $kvcobj->set('reports_list_' . $this->member['id'] . '_' . $pid . '_' . $page . '_' . $product, $reports_list);
        }


        //fb likes
        $product['_fb_likes'] = db_query_count('member_good', "section='product' and sid=" . mysql_escape_string($pid));
        $pagelist = showPage($reports_list['pageinfo']['total'], 5, $page, optimize_url('product', 'detail', 'mtype=' . $mtype . '&pid=' . $pid . '&tab=1'));

        //FG
        $h_param = $fg_arr_rs = $fg_reports = $fg_list = array();
        $h_param['pid'] = $pid;
        $fg_list = $kvcobj->get('fg_list_' . $pid);
        if (!$fg_list) {
            $fg_arr_rs = $this->FG->get_fg_product($h_param);
            if (!empty($fg_arr_rs['result'][0])) {
                $fg_list = $fg_arr_rs['result'][0];
                //$_json = !empty($fg_arr_rs['result'][0]['vote_option_json']) ? $fg_arr_rs['result'][0]['vote_option_json'] :'';
                //$fg_list['vote_option'] = json_decode($_json, 1);
            }
            $kvcobj->set('fg_list_' . $pid, $fg_list);
        }

        $h_param['page'] = $tab == 2 ? $_page : 1;
        $h_param['size'] = 5;
        $fg_reports = $kvcobj->get('fg_reports_' . $pid . '_' . $h_param['page'] . '_' . $h_param['size']);
        if (!$fg_reports) {
            $fg_reports = $this->FG->get_fg_report($h_param);
            if (!empty($fg_reports['result'])) {
                foreach ($fg_reports['result'] as $k => $v) {
                    //$_json = !empty($v['vote_option_json']) ? $v['vote_option_json'] :'';
                    //$fg_reports['result'][$k]['vote_option'] = json_decode($_json, 1);
                    $img_array = array();
                    preg_match_all('/<img.*?src=\"\/(.*?\.jpg)\".*?>/i', $v['msg'], $img_array, PREG_PATTERN_ORDER);
                    $img_array = array_unique($img_array[1]);
                    if (!empty($img_array)) {
                        foreach ($img_array as $k1 => $v1) {
                            $fg_reports['result'][$k]['pic'][$k1] = PhotoResize($v1, 163, 102);
                            if ($k1 >= 2)
                                break;
                        }
                    }
                    $fg_reports['result'][$k]['msg'] = wordscut(strip_tags($v['msg']), 100);
                    $fg_reports['result'][$k]['share_url'] = optimize_url('product', 'fg', 'mtype=' . $mtype . '&pid=' . $pid . '&rid=' . $v['id']);
                    $fg_reports['result'][$k]['title'] = str_replace(array("\r\n", "\n", "\r"), "", wordscut($v['msg'], 20));

                    $fb_result = file_get_contents("http://graph.facebook.com/" . $global_url . substr(optimize_url('product', 'fg', 'mtype=' . $mtype . '&pid=' . $pid . '&rid=' . $v['id']), 1));
                    $fb_array = json_decode($fb_result, 1);
                    $fg_reports['result'][$k]['fb_count'] = $fb_array['shares'] + $v['fb_share_num_base'];
                }
            }
            $kvcobj->set('fg_reports_' . $pid . '_' . $h_param['page'] . '_' . $h_param['size'], $fg_reports);
        }
        $fg_pagelist = showPage($fg_reports['pageinfo']['total'], $h_param['size'], $h_param['page'], optimize_url('product', 'detail', 'mtype=' . $mtype . '&pid=' . $pid . '&tab=2'));

        $meta = $this->meta;
        if ($meta) {
            foreach ($meta as $k => $v) {
                $meta[$k] = str_replace('[product]', $product['type_name'] . '-' . $product['cname'] . $product['name'], $v);
            }
        }

        $pageoptions = array();
        $pageoptions['metas'] = array(
            0 => array('property' => 'og:image', 'content' => $global_url . PhotoResize($product['_photo_url'], 100, 100)),
            1 => array('property' => 'og:description', 'content' => $product['body']),
            2 => array('property' => 'og:url', 'content' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']),
            3 => array('property' => 'og:title', 'content' => $product['type_name'] . '-' . $product['cname'] . $product['name'] . '-產品報告'),
        );

        //echo '<pre>'.var_export($fg_reports,1).'</pre>';
        $this->tmpl_assign('tab', $tab); //改為tab選項
        $this->tmpl_assign('fg_list', $fg_list);
        $this->tmpl_assign('fg_reports', $fg_reports);
        $this->tmpl_assign('fg_pagelist', $fg_pagelist);
        $this->tmpl_assign('meta', $meta);
        $this->tmpl_assign('selfurl', $this->selfurl);
        $this->tmpl_assign('pid', $pid);
        $this->tmpl_assign('t', $t);
        $this->tmpl_assign('mtype', $mtype);
        $this->tmpl_assign('product', $product);
        $this->tmpl_assign('agegroup_list', $agegroup_list);
        $this->tmpl_assign('reports_list', $reports_list);
        $this->tmpl_assign('pagelist', $pagelist);
        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));

        $pageoptions['csses'][0] = "jquery.lightbox-0.5";
        $pageoptions['jses'][0] = "jquery.lightbox-0.5.min";
        $pageoptions['csses'][1] = "fg";
        $this->tmpl_assign('pageoptions', $pageoptions);

        $this->tmpl_assign('global_url', $global_url);
        return $this->load_tmpl($tmpl);
    }

    function action_reportDetail() {
        $pid = intval($this->get_q('pid', 0, 'int'));
        $rid = intval($this->get_q('rid', 0, 'int'));
        $page = intval($this->get_q('page', '1', 'int'));
        $pview = intval($this->get_q('pview', 0, 'int'));

        if (empty($pid) || (empty($rid) && empty($pview))) {
            return showMsgCode('無效鏈接！', '/');
        }
        db_handle('update product_reports set click=click+1 where id=' . mysql_escape_string($rid));

        $kvcobj = getCache('product_reportDetail', array('expire' => KVC_EXPIRE));
        $product = $kvcobj->get($pid . '_data');
        if (!$product) {
            $product = $this->Product->get_product_byid($pid);
            $product['is_report_add'] = time() <= strtotime($product['report_starttime']) ? 0 : 1;
            $product['_diff_day'] = ceil((strtotime($product['report_endtime']) - strtotime($product['report_starttime'])) / 86400);
            $product['_photo_url'] = PhotoResize($product['cover'], 158, 158);
            $product['_overall'] = !empty($product['product_reports_stat']['scores']) ? $product['product_reports_stat']['scores'] : 0;
            if (!empty($product['price'])) {
                $product['_attr']['價格'] = '$' . $product['price'];
            }
            if (!empty($product['attribute_value1'])) {
                $product['_attr']['實際容量'] = nl2br($product['attribute_value1']);
            }
            for ($i = 2; $i < 9; $i++) {
                if (!empty($product['attribute_value' . $i])) {
                    $product['_attr'][$product['attribute_label' . $i]] = nl2br($product['attribute_value' . $i]);
                }
            }
            if (!empty($product['about_url']) && !empty($product['about_txt'])) {
                $product['_attr']['相關資料'] = "<a target='_blank' href='" . $product['about_url'] . "' target>" . nl2br($product['about_txt']) . "</a>";
            }
            //if(!empty($product['body'])){ $product['_attr']['編輯短評'] = nl2br($product['body']);}

            $kvcobj->set($pid . '_data', $product);
        }
        if (time() < strtotime($product['apply_starttime'])) {
            return showMsgCode('活動時間有誤！', '/');
        }
        $mtype = $product['member_type'];
        $tmpl = !empty($pview) ? 'p_report_preview.php' : ($mtype == 5 ? 'p_reportDetail_expert.php' : 'p_reportDetail_general.php');

        //獲得報告列表資料
        $pv_arr = array();
        if (!empty($pview)) {
            $pv_arr = array(
                'oid' => $pid,
                'mid' => $this->member['id'],
                'photo_l' => imore_avatar($this->member['photo']),
                'username' => $this->member['username'],
                'user_type' => $this->member['member_type'],
                'title' => htmlencode($this->get_q('title', '')),
                'agegroup' => intval($this->get_q('age', 1, 'int')),
                'body' => htmlencode($this->get_q('content', '')),
                'body_skin_id' => intval($this->get_q('skin', 1, 'int')),
                'well' => intval($this->get_q('well', 3, 'int')),
                '_content' => $this->get_q('pic', ''),
            );
            //用戶滿意度
            $j = 0;
            for ($i = 1; $i < 9; $i++) {
                if (isset($product['vote_option_data']['result'][$i - 1]) && !empty($product['vote_option_data']['result'][$i - 1])) {
                    $pv_arr['_category_score'][$j]['k'] = intval($this->get_q('category_score' . $i, 1, 'int'));
                    $pv_arr['_category_score'][$j]['v'] = $product['vote_option_data']['result'][$i - 1]['cname'];
                    $j++;
                }
            }
        }

        $reports_list_res = $kvcobj->get('reports_list_res_' . $this->member['id'] . '_' . $pid . '_' . $rid . '_' . $pview . '_' . $product);
        if (!$reports_list_res) {
            $reports_list_res = $this->Product->get_detail_report_one($this->member['id'], $pid, $rid, $product, $pview, $pv_arr);
            $kvcobj->set('reports_list_res_' . $this->member['id'] . '_' . $pid . '_' . $rid . '_' . $pview . '_' . $product, $reports_list_res);
        }

        $global_url = $this->param('URL');
        $fb_result = file_get_contents("http://graph.facebook.com/" . $global_url . substr($reports_list_res['share_url'], 1));
        $fb_array = json_decode($fb_result, 1);

        $reports_list_res['fb_count'] = $fb_array['shares'] + $reports_list_res['fb_share_num_base'];

        $orderby = "TB1.addtime desc,TB1.id desc";
        $reportsCommentList = $this->ProductReportsComment->getReportsCommentList($rid, $orderby, $page, $this->pagesize);
        if (!empty($reportsCommentList['result'])) {
            foreach ($reportsCommentList['result'] as $k => $v) {
                $reportsCommentList['result'][$k]['photo_l'] = imore_avatar($v['photo']);
                $reportsCommentList['result'][$k]['addtime'] = time_to_str($v['addtime']);
            }
        }

        $product['_fb_likes'] = db_query_count('member_good', "section='product' and sid=" . mysql_escape_string($pid));

        $pagelist = showPage($reportsCommentList['pageinfo']['total'], $this->pagesize, $page, optimize_url('product', 'reportDetail', 'mtype=' . $mtype . '&pid=' . $pid . '&rid=' . $rid), 0, '#messagebox');

        $uid = empty($this->member) ? 0 : $this->member['id'];
        $photo = empty($this->member) ? PhotoResize('', 58, 58) : imore_avatar($this->member['photo']);

        $reply_type = 0; //  0 -itrial 自己的留言下，自己的回覆可移除，別人的可舉報   1 -gotrip 自己的留言下，所有回覆可移除

        $meta = $this->meta;
        if ($meta) {
            foreach ($meta as $k => $v) {
                $meta[$k] = str_replace(array('[report]', '[product]'), array($reports_list_res['title'], $product['type_name'] . $product['cname']), $v);
            }
        }

        $fb_pic_array[0] = array('property' => 'og:image', 'content' => $global_url . PhotoResize($product['_photo_url'], 100, 100));
        if ($reports_list_res['_content']) {
            foreach ($reports_list_res['_content'] as $value) {
                $fb_pic_array[] = array('property' => 'og:image', 'content' => $global_url . PhotoResize($value['p'], 100, 100));
            }
        }


        $pageoptions = array();
        $fb_other_array = array(
            array('property' => 'og:description', 'content' => htmlencode($reports_list_res['body'])),
            array('property' => 'og:url', 'content' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']),
            array('property' => 'og:title', 'content' => htmlencode($reports_list_res['title'])),
        );

        $pageoptions['metas'] = array_merge($fb_pic_array, $fb_other_array);

        $this->tmpl_assign('meta', $meta);
        $this->tmpl_assign('reply_type', $reply_type);
        $this->tmpl_assign('uid', $uid);
        $this->tmpl_assign('photo', $photo);
        $this->tmpl_assign('pagelist', $pagelist);
        $this->tmpl_assign('pid', $pid);
        $this->tmpl_assign('rid', $rid);
        $this->tmpl_assign('mtype', $mtype);
        $this->tmpl_assign('product', $product);
        $this->tmpl_assign('reports_list_res', $reports_list_res);
        $this->tmpl_assign('reportsCommentList', $reportsCommentList);
        $this->tmpl_assign('memberData', $this->member);
        $this->tmpl_assign('SUPERUSER', SUPERUSER);

        $pageoptions['csses'][0] = "jquery.lightbox-0.5";
        $pageoptions['jses'][0] = "jquery.lightbox-0.5.min";
        $this->tmpl_assign('pageoptions', $pageoptions);

        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        $this->tmpl_assign('DetailUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . optimize_url('product', 'detail', 'mtype=' . $mtype . '&pid=' . $pid)));
        return $this->load_tmpl($tmpl);
    }

    function action_readReport_list() {
        $page = intval($this->get_q('page', 1, 'int'));
        $order_q = intval($this->get_q('order', 1, 'int'));
        $ptype = intval($this->get_q('ptype', 0, 'int'));
        $mtype = intval($this->get_q('mtype', 1, 'int'));
        $tmpl = $mtype == 5 ? 'p_readReport_list_expert.php' : 'p_readReport_list_general.php';

        $order = !empty($order_q) ? $order_q : 1;
        // <!--數據列表
        $orderby = '';
        switch ($order) {
            case 3:
                $orderby = "TB1.reports desc,TB1.id desc";
                break;
            case 2:
                $orderby = "scores desc,TB1.id desc";
                break;
            case 1:
            default:
                $orderby = "TB1.report_starttime desc,TB1.id desc";
                break;
        }
        $kvcobj = getCache('product_readReport_list', array('expire' => KVC_EXPIRE));


        //分類
        $product_layout_category_list = $kvcobj->get('product_layout_category_list');
        if (!$product_layout_category_list) {
            $product_layout_category_list = $this->Lookup->getLookup('product_layout_category', 0, 1, 9, 0);
            $kvcobj->set('product_layout_category_list', $product_layout_category_list);
        }

        //產品分類
        $ptype_arr = $kvcobj->get('ptype_arr');
        if (!$ptype_arr) {
            //$ptype_arr[0]['name'] = '所有分類';
            //$ptype_arr[0]['list'] = array();
            if (!empty($product_layout_category_list['result'])) {
                foreach ($product_layout_category_list['result'] as $k => $v) {
                    $ptype_arr[$v['id']]['name'] = $v['cname'];
                    $ptype_li_list = $this->Lookup->getLookup('product_layout_category', 0, 1, 99, $v['id'], $mtype);
                    if (!empty($ptype_li_list['result'])) {
                        foreach ($ptype_li_list['result'] as $k1 => $v1) {
                            if (($mtype == 5 && $v1['products_expert_num'] > 0) || ($mtype == 1 && $v1['products_trialist_num'] > 0)) {
                                $ptype_arr[$v['id']]['list'][$k1] = $v1;
                            }
                        }
                    }
                }
            }
            $kvcobj->set('ptype_arr', $ptype_arr);
        }

        $ptype_kv = array();
        $ptype_kv['k'] = $ptype;
        $ptype_temp = db_query_one('product_layout_category', array('field' => 'id,cname,topid', 'where' => 'id=' . $ptype));
        $ptype_kv['v'] = !empty($ptype_temp['result']) ? $ptype_temp['result']['cname'] : '';
        $ptype_kv['t'] = !empty($ptype_temp['result']) ? $ptype_temp['result']['topid'] : '';


        $product_list = $kvcobj->get($mtype . '_' . $order . '_' . $page . '_' . $ptype . '_product_list');
        if (!$product_list) {
            if (isset($ptype_arr[$ptype]) && !empty($ptype_arr[$ptype])) {
                $product_list = $this->Product->getProductList($mtype, 6, $orderby, $page, $this->pagesize, '', $ptype, 0, 1, 0);
            } else {
                $product_list = $this->Product->getProductList($mtype, 6, $orderby, $page, $this->pagesize, '', 0, 0, 1, $ptype);
            }
            $kvcobj->set($mtype . '_' . $order . '_' . $page . '_' . $ptype . '_product_list', $product_list);
        }
        $product_list_res = isset($product_list['result']) && !empty($product_list['result']) ? $product_list['result'] : array();
        $report_list = array();
        if ($product_list_res) {
            foreach ($product_list_res as $k => $v) {
                $product_list_res[$k]['_photo_url'] = PhotoResize($v['cover'], 100, 143);
                //總評

                $product_list_res[$k]['_overall'] = !empty($product_list_res[$k]['scores']) ? $product_list_res[$k]['scores'] : 0;

                $product_list_res[$k]['_reports'] = $product_list_res[$k]['reports'];

                $report_list[$k] = $kvcobj->get($v['id'] . '_report_list');
                if (!$report_list[$k]) {
                    $report_list[$k] = $this->ProductReports->getReportsList($v['id'], 0, 0, "TB1.priority desc,TB1.addtime desc", 1, 5, 1);
                    foreach ($report_list[$k]['result'] as $k1 => $v1) {
                        $report_list[$k]['result'][$k1]['photo_l'] = imore_avatar($v1['photo']);
                    }
                    $kvcobj->set($v['id'] . '_report_list', $report_list[$k]);
                }
                //報告總數
                $product_list_res[$k]['_rpsum'] = $report_list[$k]['pageinfo']['total'];
            }
        }


        //end 數據列表-->

        $pagelist = showPage($product_list['pageinfo']['total'], $this->pagesize, $page, optimize_url('product', 'readReport_list', 'mtype=' . $mtype . '&ptype=' . $ptype . '&order=' . $order));

        $this->tmpl_assign('pagelist', $pagelist);
        $this->tmpl_assign('ptype_arr', $ptype_arr);
        $this->tmpl_assign('ptype', $ptype);
        $this->tmpl_assign('ptype_kv', $ptype_kv);
        $this->tmpl_assign('product_list_res', $product_list_res);
        $this->tmpl_assign('order', $order);
        $this->tmpl_assign('report_list', $report_list);
        $this->tmpl_assign('mtype', $mtype);
        return $this->load_tmpl($tmpl);
    }

    function action_report_show() {
        $pid = intval($this->get_q('pid', 1, 'int'));
        $aid = intval($this->get_q('aid', 1, 'int'));
        $issub = intval($this->get_q('issubmit', 0));
        if (!$this->member) {
            $toURL = optimize_url('product', 'report_show', 'pid=' . $pid . "&aid=" . $aid . "&issubmit=" . $issub);
            $this->s_param('toURL', $toURL);
            return showMsgCode(HAS_LOGIN, '/member.php?action=login');
        }

        $c = db_query_count('product_application', "id=" . mysql_escape_string($aid) . " and (application_status=9 or application_status=11)  and  status=1");
        if ($c > 0) {
            return showMsgCode('活動已確認或拒絕', '/');
        }

        //$kvcobj = getCache('product_report_show', array('expire' => KVC_EXPIRE));
        $kvcobj1 = getCache('get_product_byid', array('expire' => KVC_EXPIRE));
        $product = $kvcobj1->get($pid);
        if (!$product) {
            $product = $this->Product->get_product_byid($pid);
            $kvcobj1->set($pid, $product);
        }

        if (time() < strtotime($product['apply_starttime'])) {
            return showMsgCode('活動時間有誤！', '/');
        }

        $product_application = $this->Product_application->getApplicationList(0, 0, "", 1, 1, $aid);
        if ($product_application['result']) {
            $result = $product_application['result'][0];
            if ($result['application_status'] <> 7) {
                return showMsgCode('審核狀態不正確', '/');
            } else {

                $c = db_query_count('member_application', "mid=" . mysql_escape_string($this->member['id']) . "  and  status=1 and product=" . mysql_escape_string($pid));
                if ($c > 0) {
                    return showMsgCode('活動已確認或拒絕', '/');
                }


                if (!empty($issub)) {
                    $or = intval($this->get_q('or', 9, 'int'));
                    if (!in_array($or, array(9, 11))) {
                        return showMsgCode('確認狀態有誤！', '/');
                    }

                    $res = db_update('product_application', array('application_status' => $or), 'id=' . mysql_escape_string($aid));
                    $msg = $or == 9 ? base64_encode(base64_encode('你已接受邀請‘' . $product['cname'] . '’，請於‘' . $product['report_endtime'] . '’前提交報告！')) : base64_encode(base64_encode('你已拒絕邀請‘' . $product['cname'] . '’！'));
                    if ($res) {
                        $_name = !empty($product['cname']) ? $product['cname'] : $product['name'];
                        if ($or == 9) {
                            $attr = array();
                            $attr['mid'] = $this->member['id'];
                            $attr['product'] = $pid;
                            $attr['delivery_status'] = 1;
                            $attr['report_starttime'] = $product['report_starttime'];
                            $attr['report_endtime'] = $product['report_endtime'];
                            //$attr['delivery_status'] = 1;
                            $attr['status'] = 1;
                            $attr['addtime'] = date('Y-m-d H:i:s');
                            db_add('member_application', $attr);
                            if ($result['from'] == 1) {
                                $this->Points->points_record($this->member['id'], "confirm_product_invite", str_replace("[產品名稱]", $_name, CONFIRM_PRODUCT_INVITE_LANG), $pid, $product['points']);
                            }
                            //sos('|confirm_product_invite|'.var_export($a,1));
                        } elseif ($or == 11) {
                            if ($result['from'] == 1) {
                                $this->Points->points_record($this->member['id'], "unfreeze_product_invite", str_replace("[產品名稱]", $_name, UNFREEZE_PRODUCT_INVITE_LANG), $pid, $product['points']);
                            }
                        }
                    }
                    $this->redirect('/member_center.php?action=invite&msg=' . $msg);
                } else {
                    $product['_photo_url'] = PhotoResize($product['cover'], 180, 180);
                    //體驗天數
                    $product['_diff_day'] = (int) ((strtotime($product['report_endtime']) - strtotime($product['report_starttime'])) / 86400);
                    //right 產品屬性info
                    $attr = array();
                    if (!empty($product['price'])) {
                        $product['_attr']['價格'] = $product['price'];
                    }
                    if (!empty($product['attribute_value1'])) {
                        $product['_attr']['實際容量'] = nl2br($product['attribute_value1']);
                    }
                    if (!empty($product['capacity_trial'])) {
                        $product['_attr']['體驗規格'] = $product['capacity_trial'];
                    }
                    for ($i = 2; $i < 9; $i++) {
                        if (!empty($product['attribute_value' . $i])) {
                            $product['_attr'][$product['attribute_label' . $i]] = nl2br($product['attribute_value' . $i]);
                        }
                    }

                    $bt_url = array();
                    $bt_url[1] = optimize_url('product', 'report_show', 'issubmit=1&pid=' . $pid . '&aid=' . $aid . '&or=9');
                    $bt_url[2] = optimize_url('product', 'report_show', 'issubmit=1&pid=' . $pid . '&aid=' . $aid . '&or=11');

                    $mtxt = $product['member_type'] == 5 ? '體驗' : '試用';
                    $this->tmpl_assign('mtxt', $mtxt);
                    $this->tmpl_assign('bt_url', $bt_url);
                    $this->tmpl_assign('data', $product);
                    $pageValue = array();
                    $pageValue['title'] = !empty($product['type_name']) ? $product['type_name'] . " - " : "";
                    $pageValue['title'] .=!empty($product['cname']) ? $product['cname'] . " - " : "";

                    $this->tmpl_assign('pageValue', $pageValue);
                    //echo '<pre>'.var_export($product,1).'</pre>';
                    return $this->load_tmpl("p_report_show.php");
                }
            }
        } else {
            return showMsgCode('id出錯', '/');
        }
    }

    function action_report_add() {
        $pid = intval($this->get_q('pid', 1, 'int'));
        
        $issubmit = $this->get_q('issubmit');
        $kvcobj = getCache('product_report_add', array('expire' => KVC_EXPIRE));

        $kvcobj1 = getCache('get_product_byid', array('expire' => KVC_EXPIRE));
        $product = $kvcobj1->get($pid);
        if (!$product) {
            $product = $this->Product->get_product_byid($pid);
            $kvcobj1->set($pid, $product);
        }

        $mtype = !empty($product['member_type']) ? $product['member_type'] : intval($this->get_q('mtype', 1, 'int'));
        //$toURL = optimize_url('product', 'report_add', 'pid=' . $pid . '&mtype=' . $mtype);
        $toURL = optimize_url('product', 'report_add', 'pid=' . $pid . '&mtype=' . $mtype);

        if (empty($this->member)) {
            $this->s_param('toURL', $toURL);
            return showMsgCode(NO_LOGIN, '/member.php?action=login');
        }

        $mem_app = db_query_one('member_application', array('field' => 'id,mid,product,is_submitted,rid,report_starttime,report_endtime', 'where' => 'product=' . $pid . ' and mid=' . $this->member['id'] . ' and status=1'));
        if ($product['member_type'] == 5) {
            if (empty($mem_app['result'])) {
                return showMsgCode('抱歉！你沒有申請此項產品的試用,所以不能提交報告！', '/');
            }
            if (!empty($mem_app['result']['is_submitted']) && $mem_app['result']['is_submitted'] == 1) {
                return showMsgCode('您已提交此活動報告！', '/');
            }
            if (time() > (strtotime($mem_app['result']['report_endtime']) + 7 * 24 * 3600)) {
                return showMsgCode('您已錯過提交報告時間！', '/');
            }
        }
        if (!empty($issubmit)) {
            $attr = array(
                'oid' => $pid,
                'mid' => $this->member['id'],
                'title' => htmlspecialchars($this->get_q('title', '')),
                //'agegroup' => intval($this->get_q('age', 1, 'int')),
                'agegroup' => $this->member['agegroup'],
                'body_skin' => intval($this->get_q('skin', 1, 'int')),
                'well' => intval($this->get_q('well', 1, 'int')),
                'body' => htmlspecialchars($this->get_q('content', '')),
            );
            for ($i = 1; $i < 9; $i++) {
                $attr['category_score' . $i] = intval($this->get_q('category_score' . $i, 0, 'int'));
            }
            $other = array(
                'pic' => $this->get_q('pic', ''),
                'pic_c' => $this->get_q('pic_c', ''),
                'body_size' => $this->get_q('content_size', 1, 'int'),
                'mem_app' => !empty($mem_app['result']) ? $mem_app['result'] : array(),
                'is_draft' => $this->get_q('is_draft', 0, 'int'),
            );
            $global_url = $this->param('URL');
            $iret = $this->Product->report_add_submit_updb($attr, $other, $product, 0, 0, $global_url);
            if (is_array($iret))
                $this->iframeReturn($iret[0], $iret[1], $iret[2]);
        } else {

            $start_time = $mem_app['result']['report_starttime'] ? $mem_app['result']['report_starttime'] : $product['report_starttime'];
            if (time() < strtotime($start_time)) {

                return showMsgCode('活動時間有誤！', '/');
            }

            $product['_photo_url'] = PhotoResize($product['cover'], 180, 180);

            //體驗天數
            $product['_diff_day'] = (int) ((strtotime($product['report_endtime']) - strtotime($product['report_starttime'])) / 86400);

            //right 產品屬性info
            if (!empty($product['attribute_value1'])) {
                $product['_attr']['實際容量'] = nl2br($product['attribute_value1']);
            }
            for ($i = 2; $i < 9; $i++) {
                if (!empty($product['attribute_value' . $i])) {
                    $product['_attr'][$product['attribute_label' . $i]] = nl2br($product['attribute_value' . $i]);
                }
            }

            $agegroup = $kvcobj->get('agegroup');
            if (!$agegroup) {
                $agegroup = $this->Lookup->getLookup('agegroup'); //年齡段
                $kvcobj->set('agegroup', $agegroup);
            }
            $body_skin = $kvcobj->get('body_skin');
            if (!$body_skin) {
                $body_skin = $this->Lookup->getLookup('body_skin'); //膚質
                $kvcobj->set('body_skin', $body_skin);
            }
            $product_reports_well = $kvcobj->get('product_reports_well');
            if (!$product_reports_well) {
                $product_reports_well = $this->Lookup->getLookup('product_reports_well'); //滿意度  很好、好
                $kvcobj->set('product_reports_well', $product_reports_well);
            }

            $vote_option_data = $product['vote_option_data']; //好評  美白度
            //echo '<pre>'.var_export($data3,1).'</pre>';
            $product['my_report_endtime'] = $mem_app['result']['report_endtime'];

            $arr5_10 = array();
            for ($i = 1; $i <= $product['max_pic_num']; $i++) {
                $arr5_10[] = $i;
            }
            $arr5 = array(1, 2, 3, 4, 5);
            $mtxt = $mtype == 5 ? '體驗' : '試用';
            $this->tmpl_assign('show_draft_bt', ((!empty($mem_app['result']) && $mem_app['result']['is_submitted'] == 0) ? 1 : 0));
            $this->tmpl_assign('mtxt', $mtxt);
            $this->tmpl_assign('arr5', $arr5);
            $this->tmpl_assign('arr5_10', $arr5_10);
            $this->tmpl_assign('selfurl', $this->selfurl);
            $this->tmpl_assign('pid', $pid);
            $this->tmpl_assign('mtype', $mtype);
            $this->tmpl_assign('product', $product);
            $this->tmpl_assign('toURL', $toURL);
            $this->tmpl_assign('agegroup', $agegroup);
            $this->tmpl_assign('body_skin', $body_skin);
            $this->tmpl_assign('product_reports_well', $product_reports_well);
            $this->tmpl_assign('vote_option_data', $vote_option_data);

            $pageValue = array();
            $pageValue['title'] = !empty($product['type_name']) ? $product['type_name'] . " - " : "";
            $pageValue['title'] .=!empty($product['cname']) ? $product['cname'] . " - " : "";

            $this->tmpl_assign('pageValue', $pageValue);
            return $this->load_tmpl("p_report_add.php");
        }
    }

    function action_ajax() {
        $t = intval($this->get_q('t', 1, 'int'));
        switch ($t) {
            case 1:
                //更多留言回覆列表
                $topid = intval($this->get_q('topid', 1, 'int'));
                $page = intval($this->get_q('page', 1, 'int'));
                $kvcobj = getCache('product_ajax', array('expire' => KVC_EXPIRE));
                $data = $kvcobj->get($t . '_' . $topid . '_' . $page . '_data');
                if (!$data) {
                    $data = $this->ProductReportsComment->getReportsSubCommentList($topid, "TB1.id desc", $page, 2);
                    $_res = db_query_one('product_reports_comment', array('field' => 'mid', 'where' => 'id=' . $topid));
                    if ($data['result']) {
                        foreach ($data['result'] as $k => $v) {
                            $data['result'][$k]['photo_l'] = imore_avatar($v['photo']);
                            $data['result'][$k]['top_mid'] = $_res['result']['mid'];
                            $data['result'][$k]['addtime'] = time_to_str($v['addtime']);
                        }
                    }
                    $kvcobj->set($t . '_' . $topid . '_' . $page . '_data', $data);
                }
                //print_r($data);
                exit(json_encode($data));
                break;
            case 2:
                //報告留言、回覆
                if (empty($this->member)) {
                    $this->iframeReturn(null, 'callback', array('retcode' => 1, 'msg' => NO_LOGIN));
                }
                $attr = array();
                $attr['oid'] = intval($this->get_q('rid', 1, 'int'));
                $attr['topid'] = intval($this->get_q('linkid', 0, 'int'));
                $attr['mid'] = $this->member['id'];
                $attr['body'] = nl2br($this->get_q('message', ''));
                $attr['status'] = 1;
                $attr['addtime'] = date("Y-m-d H:i:s");
                $attr['likes'] = 0;
                $attr['unlikes'] = 0;
                if (empty($attr['body'])) {
                    $this->iframeReturn(null, 'callback', array('retcode' => 5, 'msg' => ERR_RESPONSES_EMPTY));
                }

                $retcode = 5;
                $retmsg = 'success';
                $res = db_add('product_reports_comment', $attr);
                if ($res) {
                    $_title = db_query_one("product_reports", array('field' => 'title', 'where' => 'id=' . $attr['oid']));
                    $this->Points->points_record($this->member['id'], "submit_comment", str_replace("[報告名稱]", $_title['result']['title'], SUBMIT_COMMENT_LANG));

                    $attr['id'] = $res;
                    //$attr['body'] = $_body;
                    $attr['username'] = $this->member['username'];
                    $attr['photo_l'] = imore_avatar($this->member['photo']);

                    if (empty($attr['topid'])) {
                        $res1 = db_query_one('product_reports', array('field' => 'comments', 'where' => ' id=' . $attr['oid']));
                        $reps = $res1['result']['comments'] + 1;
                        db_update('product_reports', array('comments' => $reps), ' id=' . mysql_escape_string($attr['oid']));

                        $attr['sum'] = 0;
                        $retcode = 3;
                        $retmsg = 'error';
                    } else {
                        $_sum = intval($this->get_q('sum', 0, 'int'));
                        $attr['sum'] = $_sum + 1;
                        db_update('product_reports_comment', array('subComments' => $attr['sum']), 'id=' . mysql_escape_string($attr['topid']));
                        $retcode = 2;
                        $retmsg = 'error';
                    }
                }
                $attr['addtime'] = '剛剛';
                $this->iframeReturn($attr, 'callback', array('retcode' => $retcode, 'msg' => $retmsg));
                break;
            case 3:
                //product、report、comments的like and notLike
                if (!empty($this->member)) {
                    $sec = $this->get_q('sec', '');
                    $sid = intval($this->get_q('sid', 0, 'int'));
                    $type = intval($this->get_q('type', 1, 'int')); // 回覆good bad
                    $attr = array();
                    $attr['section'] = $sec;
                    $attr['mid'] = $this->member['id'];
                    $attr['sid'] = $sid;
                    $attr['addtime'] = date('Y-m-d H:i:s');
                    $c = db_query_count('member_like', "section='" . $sec . "' and mid=" . mysql_escape_string($this->member['id']) . " and sid=" . mysql_escape_string($sid));
                    $recode = $likes = 0;
                    $like_field = ($sec == 'comment' && $type == 2) ? 'unlikes' : 'likes';
                    if ($c < 1) {
                        $res = db_add('member_like', $attr);
                        if ($res > 0) {
                            switch ($sec) {
                                case 'product': $tbn = 'product';
                                    break;
                                case 'report': $tbn = 'product_reports';
                                    break;
                                case 'comment': $tbn = 'product_reports_comment';
                                    break;
                                case 'fg_report': $tbn = 'fg_report';
                                    break;
                                default : exit;
                            }
                            $_data = db_query_one($tbn, array('field' => $like_field, 'where' => 'id=' . $sid . ' and status=1'));
                            $likes = intval($_data['result'][$like_field]) + 1;
                            $res1 = db_update($tbn, array($like_field => $likes), 'id=' . mysql_escape_string($sid) . ' and status=1');
                            $recode = empty($res1) ? $recode : 1;
                            if ($sec == 'product') {
                                $_data = db_query_one('product', array('field' => 'likes_offset,name,cname', 'where' => 'id=' . $sid . ' and status=1'));
                                $likes = $likes + intval($_data['result']['likes_offset']);
                                $_name = !empty($_data['result']['cname']) ? $_data['result']['cname'] : $_data['result']['name'];
                                $this->Points->points_record($this->member['id'], "like_product", str_replace("[產品名稱]", $_name, LIKE_PRODUCT_LANG));
                            } elseif ($sec == 'report') {
                                $_data = db_query_one('product_reports', array('field' => 'likes_num_base,title,mid', 'where' => 'id=' . $sid . ' and status=1'));
                                if ($likes == 30)
                                    $this->Points->points_record($_data['result']['mid'], "be_liked_report_30", str_replace("[報告名稱]", $_data['result']['title'], BE_LIKED_REPORT_30_LANG));
                                $this->Points->points_record($this->member['id'], "like_report", str_replace("[報告名稱]", $_data['result']['title'], LIKE_REPORT_LANG));
                                $likes = $likes + intval($_data['result']['likes_num_base']);
                            } elseif ($sec == 'fg_report') {
                                $_data = db_query_one('fg_report', array('field' => 'likes_num_base', 'where' => 'id=' . $sid . ' and status=1'));
                                $likes = $likes + intval($_data['result']['likes_num_base']);
                            }
                        }
                    }
                    echo json_encode(array('recode' => $recode, 'likes' => $likes, 'msg' => HAS_LIKES));
                } else {
                    echo json_encode(array('recode' => 2, 'likes' => 0, 'msg' => NO_LOGIN));
                }
                exit();
                break;
            case 4:
                //留言舉報
                if (empty($this->member)) {
                    echo json_encode(array('recode' => 0, 'msg' => NO_LOGIN));
                    exit();
                }
                $attr = array();
                $attr['comment_id'] = intval($this->get_q('id', 1, 'int'));
                $attr['comment_mid'] = intval($this->get_q('mid', 1, 'int')); //被舉報者
                $attr['inform_mid'] = $this->member['id']; ////////舉報者
                $attr['addtime'] = date("Y-m-d H:i:s");

                $c = db_query_count('comment_inform', "comment_id=" . mysql_escape_string($attr['comment_id']) . " and comment_mid=" . mysql_escape_string($attr['comment_mid']) . " and inform_mid=" . mysql_escape_string($attr['inform_mid']));
                if ($c > 0) {
                    echo json_encode(array('recode' => 2, 'msg' => HAS_COMMENT));
                    exit();
                }
                $res = db_add('comment_inform', $attr);
                echo json_encode(array('recode' => 1, 'msg' => ''));
                exit();
                break;
            case 5:
                //刪除留言、回覆
                $id = intval($this->get_q('id', 0, 'int'));
                $topid = intval($this->get_q('topid', 0, 'int'));
                $sum = intval($this->get_q('sum', 0, 'int'));
                $is = intval($this->get_q('is', 0, 'int'));

                $res = db_update('product_reports_comment', array('status' => 0), 'id=' . mysql_escape_string($id));
                if (!empty($is)) {
                    $res = db_query_one('product_reports_comment', array('field' => 'oid', 'where' => ' id=' . $id));
                    $res1 = db_query_one('product_reports', array('field' => 'comments', 'where' => ' id=' . $res['result']['oid']));
                    $reps = $res1['result']['comments'] - 1;
                    db_update('product_reports', array('comments' => $reps), ' id=' . mysql_escape_string($res['result']['oid']));
                }
                if (!empty($topid)) {
                    db_update('product_reports_comment', array('subComments' => ($sum - 1)), 'id=' . mysql_escape_string($topid));
                }
                echo $res;
                exit();
                break;
            case 6:
                //上傳申請頭像
                $root = $this->param('WWW');
                $upload_status = uploadfiles($root . '/upload/invite', 'temp', "jpg,jpeg,gif,png", 5 * 1020 * 1024);

                $kk = $this->get_q('k', '');
                if ($upload_status) {
                    foreach ($upload_status as $k => $v) {
                        if ($v['code'] === 1) {
                            $upload_status[$k]['src'] = str_replace($root . '/', '', $upload_status[$k]['path']);
                            $upload_status[$k]['thumb'] = PhotoResize($upload_status[$k]['src'], 84, 84);
                            $upload_status[$k]['k'] = $kk;
                        }
                    }
                }
                echo '<script>' . str_replace('$res', json_encode($upload_status), $_POST['callback_script']) . '</script>';
                break;
            /*
              case 7:
              //移除上傳的圖片
              $pic1 = $this->get_q('pic1', '');
              $pic2 = $this->get_q('pic2', '');
              if (!empty($pic1) && !empty($pic1)) {
              unlink($pic1);
              unlink($pic2);
              echo '1';
              } else {
              echo 'error';
              }
              break;
             */
            case 8:
                //上傳報告圖片
                $root = $this->param('WWW');
                $upload_status = uploadfiles($root . '/upload/report');
                $pic_id = $this->get_q('pic_id', '');
                if ($upload_status) {
                    foreach ($upload_status as $k => $v) {
                        if ($v['code'] === 1) {
                            $upload_status[$k]['src'] = str_replace($root . '/', '', $upload_status[$k]['path']);
                            $upload_status[$k]['thumb'] = PhotoResize($upload_status[$k]['src'], 100, 100);
                            $upload_status[$k]['pic_id'] = $pic_id;
                        }
                    }
                }
                echo '<script>' . str_replace('$res', json_encode($upload_status), $_POST['callback_script']) . '</script>';
                break;
            /*
              case 9:
              //用戶遲交報告狀態更新
              $pid = intval($this->get_q('pid', 0, 'int'));
              $_date_res = db_query_one('member_application', array('field' => 'report_endtime', 'where' => 'product=' . $pid . ' and mid=' . $this->member['id']));
              $_date = date('Y-m-d H:i:s', strtotime($_date_res['result']['report_endtime']) + 604800);
              $res = db_update('member_application', array('is_member_delay' => 1, 'report_endtime' => $_date), 'product=' . mysql_escape_string($pid) . ' and mid=' . mysql_escape_string($this->member['id']));
              if ($res) {
              $attr = array();
              $data = $this->Product->get_product_byid($pid);
              $attr['pid'] = $pid;
              $attr['type_name'] = $data['type_name'];
              $attr['cname'] = $data['cname'];
              $attr['date'] = $_date;
              $attr['date_l'] = date('Y-m-d', strtotime($_date));
              }
              $this->iframeReturn($attr, 'callback', array('retcode' => 1, 'msg' => 'success'));
              break;
             */
            case 10:
                //用戶申請產品試用bt狀態判斷
                $ret = array();
                if (!empty($this->member)) {
                    $ret['login'] = 1;

                    $_mem1 = $this->ModelMember->getMember($this->member['id']);
                    if ($_mem1['result'][0]['email_status'] != 1) {
                        $ret['email'] = 0;
                        echo json_encode($ret);
                        exit();
                    } else {
                        $ret['email'] = 1;
                    }

                    $_mem = $this->ModelMember->getMemberCondition($this->member['id']);
                    $_member_arr = array();
                    if ($_mem['result'])
                        $_member_arr = $_mem['result'][0];

                    $pid = intval($this->get_q('pid', 0, 'int'));
                    $_pdata = db_query_one('product', array('field' => 'member_type,points,name,cname', 'where' => 'id=' . $pid));

                    if (empty($_member_arr['address'])) {
                        $ret['limit'] = 0;
                        $ret['msg'] = LIMIT_INVITE;
                        echo json_encode($ret);
                        exit();
                    } elseif ((empty($_member_arr['homepage'])) && intval($_pdata['result']['member_type']) == 5) {
                        $ret['limit'] = 0;
                        $ret['msg'] = LIMIT_INVITE_EXPERIENCE;
                        echo json_encode($ret);
                        exit();
                    } else {
                        $ret['limit'] = 1;
                    }

                    $_data = db_query_count('product_application', "oid=" . mysql_escape_string($pid) . " and mid=" . mysql_escape_string($this->member['id']));
                    if ($_data > 0) {
                        $ret['invite'] = 0;
                        $ret['msg'] = HAS_APPLY;
                        echo json_encode($ret);
                        exit();
                    } else {
                        $ret['invite'] = 1;
                    }

                    if (intval($_mem1['result'][0]['points']) < intval($_pdata['result']['points'])) {
                        $ret['invite'] = 0;
                        $_name = !empty($_pdata['result']['cname']) ? $_pdata['result']['cname'] : $_pdata['result']['name'];
                        $ret['msg'] = '您的積分不足，無法申請產品 - ' . $_name;
                        echo json_encode($ret);
                        exit();
                    }
                } else {
                    $ret['login'] = 0;
                    $ret['msg'] = NO_LOGIN;
                }
                echo json_encode($ret);
                exit();
                break;
            case 11:
                //用戶寫心得bt狀態判斷
                $ret = array();
                if (!empty($this->member)) {//是否登錄
                    $ret['login'] = 1;
                    $pid = intval($this->get_q('pid', 0, 'int'));

                    $_mem = $this->ModelMember->getMemberCondition($this->member['id']);
                    $_mem1 = $this->ModelMember->getMember($this->member['id']);
                    if ($_mem1['result'][0]['email_status'] != 1) {
                        $ret['email'] = 0;
                        echo json_encode($ret);
                        exit();
                    } else {
                        $ret['email'] = 1;
                    }
                    $_member_arr = array();
                    if ($_mem['result'])
                        $_member_arr = $_mem['result'][0];
                    $_pdata = db_query_one('product', array('field' => 'member_type', 'where' => 'id=' . $pid));

                    if (empty($_member_arr['address'])) {//是否會員資格
                        $ret['limit'] = 0;
                        //$ret['msg'] = LIMIT_INVITE;
                        echo json_encode($ret);
                        exit();
                    } elseif ((empty($_member_arr['homepage'])) && intval($_pdata['result']['member_type']) == 5) {
                        $ret['limit'] = 0;
                        //$ret['msg'] = LIMIT_INVITE_EXPERIENCE;
                        echo json_encode($ret);
                        exit();
                    } else {
                        $ret['limit'] = 1;
                        $_data = db_query_one('member_application', array('field' => 'is_submitted', 'where' => 'mid=' . $this->member['id'] . ' and product=' . $pid . ' and status=1'));

                        $_data1 = db_query_one('product', array('field' => 'report_starttime,report_endtime', 'where' => 'id=' . $pid));

                        if (!empty($_data['result'])) {//是否通過申請
                            if (intval($_data['result']['is_submitted']) == 0) {//是否發表過報告
                                if (time() >= strtotime($_data1['result']['report_starttime']) && time() <= strtotime($_data1['result']['report_endtime'])) {
                                    $ret['s'] = 2;
                                } elseif (time() >= strtotime($_data1['result']['report_endtime']) && time() <= (strtotime($_data1['result']['report_endtime']) + 7 * 24 * 3600)) {
                                    $ret['s'] = 3;
                                } else {
                                    $res['s'] = 4;
                                }
                            } else {
                                $ret['s'] = 5; //發表過報告
                            }
                        } else {
                            $ret['s'] = 1; //沒申請或沒通過
                        }
                    }
                } else {
                    $ret['login'] = 0;
                    $ret['msg'] = NO_LOGIN;
                }
                echo json_encode($ret);
                exit();
                break;
            /*
              case 12:
              //檢查用戶是否有like會員
              if (!empty($this->member)) {
              $sec = $this->get_q('sec', '');
              $sid = intval($this->get_q('sid', 0, 'int'));
              $attr = array();
              $attr['section'] = $sec;
              $attr['mid'] = $this->member['id'];
              $attr['sid'] = $sid;
              $attr['addtime'] = date('Y-m-d H:i:s');
              $c = db_query_count('member_good', "section='" . mysql_escape_string($sec) . "' and mid=" . mysql_escape_string($this->member['id']) . " and sid=" . mysql_escape_string($sid));
              $cc = 0;
              if ($c < 1) {
              $res = db_add('member_good', $attr);
              if ($res > 0) {
              $cc = db_query_count('member_good', "section='" . mysql_escape_string($sec) . "' and sid=" . mysql_escape_string($sid));
              echo json_encode(array('recode' => 1, 'likes' => $cc, 'msg' => 'success'));
              } else {
              echo json_encode(array('recode' => 0, 'likes' => $cc, 'msg' => 'tb error'));
              }
              } else {
              echo json_encode(array('recode' => 0, 'likes' => $cc, 'msg' => HAS_LIKES));
              }
              } else {
              echo json_encode(array('recode' => 2, 'likes' => 0, 'msg' => NO_LOGIN));
              }
              exit();
              break;
             */
            case 13:
                //用戶提交報告bt狀態判斷
                $ret = array();
                if (!empty($this->member)) {//是否登錄
                    $ret['login'] = 1;
                    $pid = intval($this->get_q('pid', 0, 'int'));

                    $_mem = $this->ModelMember->getMemberCondition($this->member['id']);
                    $_mem1 = $this->ModelMember->getMember($this->member['id']);
                    if ($_mem1['result'][0]['email_status'] != 1) {
                        $ret['email'] = 0;
                        echo json_encode($ret);
                        exit();
                    } else {
                        $ret['email'] = 1;
                    }
                    $_member_arr = array();
                    if ($_mem['result'])
                        $_member_arr = $_mem['result'][0];
                    $_pdata = db_query_one('product', array('field' => 'member_type', 'where' => 'id=' . $pid));

                    if (empty($_member_arr['address'])) {//是否會員資格
                        $ret['limit'] = 0;
                        //$ret['msg'] = LIMIT_INVITE;
                        echo json_encode($ret);
                        exit();
                    } elseif ((empty($_member_arr['homepage'])) && intval($_pdata['result']['member_type']) == 5) {
                        $ret['limit'] = 0;
                        //$ret['msg'] = LIMIT_INVITE_EXPERIENCE;
                        echo json_encode($ret);
                        exit();
                    } else {
                        $ret['limit'] = 1;
                        $_data = db_query_count('product_application', 'mid=' . mysql_escape_string($this->member['id']) . ' and oid=' . mysql_escape_string($pid) . ' and application_status=9 and status=1');
                        $_data1 = db_query_one('product', array('field' => 'report_starttime,report_endtime', 'where' => 'id=' . $pid));

                        if ($_data > 0) {//是否申請過且通過申請
                            if (time() >= strtotime($_data1['result']['report_starttime']) && time() <= strtotime($_data1['result']['report_endtime'])) {
                                $ret['s'] = 2;
                            } elseif (time() >= strtotime($_data1['result']['report_endtime']) && time() <= (strtotime($_data1['result']['report_endtime']) + 7 * 24 * 3600)) {
                                $ret['s'] = 3;
                            } else {
                                $res['s'] = 4;
                                $ret['msg'] = "您已錯過了提交報告的時間！";
                            }
                        } else {
                            $ret['s'] = 1; //沒申請或沒通過
                            $ret['msg'] = CANNOT_REPORT;
                        }
                    }
                } else {
                    $ret['login'] = 0;
                    $ret['msg'] = NO_LOGIN;
                }
                echo json_encode($ret);
                exit();
                break;
            case 14:
                //留言登錄時，頭像異步顯示
                $photo = empty($this->member) ? PhotoResize('', 58, 58) : imore_avatar($this->member['photo']);
                echo $photo;
                break;
            case 15:
                //檢查用戶是否登錄
                if (empty($this->member)) {
                    echo 1;
                } else {
                    echo 0;
                }
                break;
            default:
                echo 'default error';
                break;
        }
    }

    function action_approveReport() {

        $pid = intval($this->get_q('pid', 1, 'int'));
        $rid = intval($this->get_q('rid', 1, 'int'));
        $key = $this->get_q('key');
        if ($key <> md5($pid . $rid . "imoreHK"))
            exit("key err");

        $_isexit1 = db_query_count('product_reports', ' id=' . mysql_escape_string($rid));
        if ($_isexit1 < 1)
            exit('輸入報告id無效！');
        //$_isexit2 = db_query_count('product_reports',' id='.$rid.' and status=1 and is_accept=1 and is_valid=1');
        //if($_isexit2>0) exit('此報告已登刊！');

        /*
          $_pr = db_query_one('product_reports', array('field' => 'mid', 'where' => 'id=' . $rid));
          //db_update('product_reports',array('is_valid'=>1,'status'=>1),'id='.$rid);
          //$res1 = db_query_one('product',array('field'=>'reports','where'=>'id='.$pid));

          $_count = db_query_count('product_reports', ' oid=' . $pid . ' and mid=' . $_pr['result']['mid'] . ' and is_valid=1');

          if (intval($_count) > 1) {
          db_update('product_reports', array('is_valid' => 0), ' oid=' . $pid . ' and mid=' . $_pr['result']['mid'] . ' and id !=' . $rid);
          }
         */
        //$reps = intval($res1['result']['reports']) + 1;
        $_rc = db_query_count('product_reports', ' oid=' . mysql_escape_string($pid) . ' and status=1 and is_accept=1');
        db_update('product', array('reports' => $_rc, 'modifiedby' => 1, 'lastmodify' => date('Y-m-d H:i:s')), ' id=' . mysql_escape_string($pid));


        $product_data = db_query_one('product', array('where' => 'id =' . $pid . ' and status=1'));
        if ($product_data['result']) {

            $value = $product_data['result'];

            $count = db_query_count('product', "product_layout_category=" . mysql_escape_string($value['product_layout_category']) . " AND `is_trial` =1 AND `is_live` =1 AND `status` =1 and member_type=" . mysql_escape_string($value['member_type']) . " and reports>0");
            $products_type_num_name = ($value['member_type'] == 5) ? "products_expert_num" : "products_trialist_num";
            db_update('product_layout_category', array($products_type_num_name => $count), 'id=' . mysql_escape_string($value['id']));


            $id = $value['id'];


            $well = $this->dbMove->product_reports_average('well', $id);
            $category_score1 = $this->dbMove->product_reports_average('category_score1', $id);
            $category_score2 = $this->dbMove->product_reports_average('category_score2', $id);
            $category_score3 = $this->dbMove->product_reports_average('category_score3', $id);
            $category_score4 = $this->dbMove->product_reports_average('category_score4', $id);
            $category_score5 = $this->dbMove->product_reports_average('category_score5', $id);
            $category_score6 = $this->dbMove->product_reports_average('category_score6', $id);
            $category_score7 = $this->dbMove->product_reports_average('category_score7', $id);
            $category_score8 = $this->dbMove->product_reports_average('category_score8', $id);

            $data = $this->dbMove->product_reports_groupby('well', $id);

            $count_well1 = $count_well2 = $count_well3 = $count_well4 = $count_well5 = 0;
            $count_agegroup1 = $count_agegroup2 = $count_agegroup3 = $count_agegroup4 = $count_agegroup5 = $count_agegroup6 = 0;

            if ($data) {
                foreach ($data as $key => $value) {
                    switch ($value['well']) {
                        case 1:
                            $count_well1 = $value['count'];
                            break;
                        case 2:
                            $count_well2 = $value['count'];
                            break;
                        case 3:
                            $count_well3 = $value['count'];
                            break;
                        case 4:
                            $count_well4 = $value['count'];
                            break;
                        case 5:
                            $count_well5 = $value['count'];
                            break;
                        default:
                            break;
                    }
                }
            }

            $data_agegroup = $this->dbMove->product_reports_groupby('agegroup', $id);
            if ($data_agegroup) {
                foreach ($data_agegroup as $key => $value) {
                    switch ($value['agegroup']) {
                        case 1:
                            $count_agegroup1 = $value['count'];
                            break;
                        case 2:
                            $count_agegroup2 = $value['count'];
                            break;
                        case 3:
                            $count_agegroup3 = $value['count'];
                            break;
                        case 4:
                            $count_agegroup4 = $value['count'];
                            break;
                        case 5:
                            $count_agegroup5 = $value['count'];
                            break;
                        case 6:
                            $count_agegroup6 = $value['count'];
                            break;
                        default:
                            break;
                    }
                }
            }
            $insert_data = array();
            $insert_data['id'] = $id;
            $insert_data['oid'] = $id;
            $insert_data['well'] = !empty($well) ? $well : 0;
            $insert_data['category_score_num'] = intval($count_well1 + $count_well2 + $count_well3 + $count_well4 + $count_well5) > 0 ? ($count_well1 + $count_well2 + $count_well3 + $count_well4 + $count_well5) : 0;
            $insert_data['category_score1'] = !empty($category_score1) ? $category_score1 : 0;
            $insert_data['category_score2'] = !empty($category_score2) ? $category_score2 : 0;
            $insert_data['category_score3'] = !empty($category_score3) ? $category_score3 : 0;
            $insert_data['category_score4'] = !empty($category_score4) ? $category_score4 : 0;
            $insert_data['category_score5'] = !empty($category_score5) ? $category_score5 : 0;
            $insert_data['category_score6'] = !empty($category_score6) ? $category_score6 : 0;
            $insert_data['category_score7'] = !empty($category_score7) ? $category_score7 : 0;
            $insert_data['category_score8'] = !empty($category_score8) ? $category_score8 : 0;
            $insert_data['well_score_num1'] = !empty($count_well1) ? $count_well1 : 0;
            $insert_data['well_score_num2'] = !empty($count_well2) ? $count_well2 : 0;
            $insert_data['well_score_num3'] = !empty($count_well3) ? $count_well3 : 0;
            $insert_data['well_score_num4'] = !empty($count_well4) ? $count_well4 : 0;
            $insert_data['well_score_num5'] = !empty($count_well5) ? $count_well5 : 0;
            $insert_data['agegroup1'] = !empty($count_agegroup1) ? $count_agegroup1 : 0;
            $insert_data['agegroup2'] = !empty($count_agegroup2) ? $count_agegroup2 : 0;
            $insert_data['agegroup3'] = !empty($count_agegroup3) ? $count_agegroup3 : 0;
            $insert_data['agegroup4'] = !empty($count_agegroup4) ? $count_agegroup4 : 0;
            $insert_data['agegroup5'] = !empty($count_agegroup5) ? $count_agegroup5 : 0;
            $insert_data['agegroup6'] = !empty($count_agegroup6) ? $count_agegroup6 : 0;


            $s = 0;
            $ii = 0;
            if ($insert_data['category_score1']) {
                $s = $s + $insert_data['category_score1'] * 100 / 5;
                $ii = $ii + 1;
            }
            if ($insert_data['category_score2']) {
                $s = $s + $insert_data['category_score2'] * 100 / 5;
                $ii = $ii + 1;
            }
            if ($insert_data['category_score3']) {
                $s = $s + $insert_data['category_score3'] * 100 / 5;
                $ii = $ii + 1;
            }
            if ($insert_data['category_score4']) {
                $s = $s + $insert_data['category_score4'] * 100 / 5;
                $ii = $ii + 1;
            }
            if ($insert_data['category_score5']) {
                $s = $s + $insert_data['category_score5'] * 100 / 5;
                $ii = $ii + 1;
            }
            if ($insert_data['category_score6']) {
                $s = $s + $insert_data['category_score6'] * 100 / 5;
                $ii = $ii + 1;
            }
            if ($insert_data['category_score7']) {
                $s = $s + $insert_data['category_score7'] * 100 / 5;
                $ii = $ii + 1;
            }
            if ($insert_data['category_score8']) {
                $s = $s + $insert_data['category_score8'] * 100 / 5;
                $ii = $ii + 1;
            }


            $w = !empty($insert_data['category_score_num']) ? (100 * $insert_data['well_score_num1'] + 75 * $insert_data['well_score_num2'] + 50 * $insert_data['well_score_num3'] + 25 * $insert_data['well_score_num4'] + 0) / $insert_data['category_score_num'] : 0;


            $scores = !empty($ii) ? (($s / $ii) * 0.7 + $w * 0.3) : $w * 0.3;

            $insert_data['scores'] = $scores;

            $product_reports_stat_data = db_query_one('product_reports_stat', array('where' => 'oid =' . $id));

            $insert_data['scores_base'] = $product_reports_stat_data['scores_base'];
            $insertkeyvalue = $insertvalue = '';
            if ($insert_data) {
                foreach ($insert_data as $key => $result) {
                    $insertkeyvalue.= $insertkeyvalue ? " ," . $key : $key;
                    $insertvalue.= $insertvalue ? " ,'" . mysql_escape_string($result) . "'" : "'" . mysql_escape_string($result) . "'";
                }
            }

            $sql = "REPLACE INTO  product_reports_stat  ($insertkeyvalue)
			VALUES($insertvalue)";

            db_handle($sql);
        }

        exit("報告登刊成功");
    }

    function action_emailApplication() {
        $aid = intval($this->get_q('aid', 1, 'int'));
        $key = $this->get_q('key');
        //echo md5($aid . "imoreHK");

        if ($key <> md5($aid . "imoreHK"))
            exit("key error");
        $kvcobj = getCache('product_emailApplication', array('expire' => KVC_EXPIRE));

        $res = $this->Product_application->getApplicationList(0, 0, "", 1, 1, $aid);

        if ($res['result']) {
            $result = $res['result'][0];
            if ($result['application_status'] <> 7) {
                exit("審核狀態不正確");
            } else {

                $global_url = $this->param('URL');
                $pid = $result['oid'];
                $product = $kvcobj->get($pid . '_data');
                if (!$product) {
                    $product = $this->Product->get_product_byid($pid);
                    $product['_photo_url'] = PhotoResize($product['cover'], 180, 180);
                    //體驗天數
                    $product['_diff_day'] = (int) ((strtotime($product['report_endtime']) - strtotime($product['apply_starttime'])) / 86400);
                    //right 產品屬性info

                    if (!empty($product['price'])) {
                        $product['_attr']['價格'] = $product['price'];
                    }
                    if (!empty($product['attribute_value1'])) {
                        $product['_attr']['實際容量'] = nl2br($product['attribute_value1']);
                    }
                    if (!empty($product['capacity_trial'])) {
                        $product['_attr']['體驗規格'] = $product['capacity_trial'];
                    }
                    for ($i = 2; $i < 9; $i++) {
                        if (!empty($product['attribute_value' . $i])) {
                            $product['_attr'][$product['attribute_label' . $i]] = nl2br($product['attribute_value' . $i]);
                        }
                    }

                    $kvcobj->set($pid . '_data', $product);
                }
                $bt_url = $global_url . optimize_url('product', 'report_show', 'pid=' . $pid . '&aid=' . $aid);

                $mtxt = $product['member_type'] == 5 ? '體驗' : '試用';
                $try_name = $product['member_type'] == 5 ? '體驗達人' : '試用專員';
                $this->tmpl_assign('mtxt', $mtxt);
                $this->tmpl_assign('bt_url', $bt_url);
                $this->tmpl_assign('data', $product);
                $this->tmpl_assign('result', $result);
                $pageValue['title'] = !empty($product['type_name']) ? $product['type_name'] . " - " : "";
                $pageValue['title'] .=!empty($product['cname']) ? $product['cname'] . " - " : "";

                $this->tmpl_assign('pageValue', $pageValue);
                $this->tmpl_assign('global_url', $global_url);

                $emailbody = $this->load_tmpl("p_report_show_email.php");

                $h_param = array(
                    'username' => $result['username'],
                    'mtxt' => $mtxt,
                    'cname' => $product['cname'],
                    'accept_endtime' => $result['accept_endtime'],
                    'bt_url' => $bt_url,
                    'report_endtime' => $product['report_endtime'],
                    'try_name' => $try_name,
                    'emailbody' => $emailbody
                );

                $this->email_obj->send($result['mid'], "invited_to_try_p", $h_param);

                echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />email發送成功";
            }
        } else {
            exit("id出錯");
        }
    }

    function action_report_edit() {
        
        $rid = intval($this->get_q('rid', 1, 'int'));
        $pid = intval($this->get_q('pid', 1, 'int'));
        //$mtype = intval($this->get_q('mtype', 1, 'int'));
        $issubmit = $this->get_q('issubmit');
        $kvcobj = getCache('product_report_edit', array('expire' => KVC_EXPIRE));
        $kvcobj1 = getCache('get_product_byid', array('expire' => KVC_EXPIRE));
        $product = $kvcobj1->get($pid);
        if (!$product) {
            $product = $this->Product->get_product_byid($pid);
            $kvcobj1->set($pid, $product);
        }

        $mtype = !empty($product['member_type']) ? $product['member_type'] : intval($this->get_q('mtype', 1, 'int'));
        //$toURL = optimize_url('product', 'report_edit', 'pid=' . $pid . '&mtype=' . $mtype);
        $toURL = optimize_url('product', 'report_edit', 'pid=' . $pid . '&rid=' . $rid . '&mtype=' . $mtype);

        if (empty($this->member)) {
            $this->s_param('toURL', $toURL);
            return showMsgCode(NO_LOGIN, '/member.php?action=login');
        }

        $mem_app = db_query_one('member_application', array('field' => 'id,mid,product,is_submitted,rid,report_starttime,report_endtime', 'where' => 'product=' . $pid . ' and mid=' . $this->member['id'] . ' and status=1'));
        if ($this->member['id'] <> SUPERUSER) {
            if (empty($mem_app['result'])) {
                return showMsgCode('抱歉！你沒有申請此項產品的試用,所以不能提交報告！', '/');
            }
        }

        if (!empty($issubmit)) {
            $attr = array(
                'oid' => $pid,
                'mid' => $this->member['id'],
                'title' => htmlspecialchars($this->get_q('title', '')),
                //'agegroup' => intval($this->get_q('age', 1, 'int')),
                'agegroup' => $this->member['agegroup'],
                'body_skin' => intval($this->get_q('skin', 1, 'int')),
                'well' => intval($this->get_q('well', 1, 'int')),
                'body' => htmlspecialchars($this->get_q('content', '')),
            );
            for ($i = 1; $i < 9; $i++) {
                $attr['category_score' . $i] = intval($this->get_q('category_score' . $i, 0, 'int'));
            }
            $other = array(
                'pic' => $this->get_q('pic', ''),
                'pic_c' => $this->get_q('pic_c', ''),
                'body_size' => $this->get_q('content_size', 1, 'int'),
                'mem_app' => !empty($mem_app['result']) ? $mem_app['result'] : array(),
                'is_draft' => $this->get_q('is_draft', 0, 'int'),
            );
            $global_url = $this->param('URL');
            $iret = $this->Product->report_add_submit_updb($attr, $other, $product, 1, $rid, $global_url);
            if (is_array($iret))
                $this->iframeReturn($iret[0], $iret[1], $iret[2]);
        } else {
            $start_time = $mem_app['result']['report_starttime'] ? $mem_app['result']['report_starttime'] : $product['report_starttime'];
            if (time() < strtotime($start_time)) {

                return showMsgCode('活動時間有誤！', '/');
            }
            //sos($pid . '_' . $rid . '_product_report');
            $product_report = $kvcobj->get($pid . '_' . $rid . '_product_report');
            if (!$product_report) {
                $product_report = $this->ProductReports->getReportsList($pid, 0, $rid, 'TB1.id desc', 1, 1, 0, "", 0, 0, 2, 0, 0);
                $kvcobj->set('product_report', $product_report);
            }
            //sos('<pre>'.var_export($product_report, 1).'</pre>');
            if (empty($product_report['pageinfo']['total'])) {
                return showMsgCode('此報告不存在或狀態有誤！', '/');
            }
            $product_report_res = !empty($product_report['result'][0]) ? $product_report['result'][0] : array();
            $product_report_res['pic_arr'] = empty($product_report_res['content_json']) ? array() : json_decode($product_report_res['content_json'], 1);
            if (!empty($product_report_res['pic_arr'])) {
                foreach ($product_report_res['pic_arr'] as $k => $v) {
                    $product_report_res['pic_arr'][$k]['p1'] = empty($v['p']) ? '' : PhotoResize($v['p'], 100, 100);
                }
            }

            $product['_photo_url'] = PhotoResize($product['cover'], 180, 180);

            //體驗天數
            $product['_diff_day'] = (int) ((strtotime($product['report_endtime']) - strtotime($product['report_starttime'])) / 86400);
            //right 產品屬性info
            if (!empty($product['attribute_value1'])) {
                $product['_attr']['實際容量'] = nl2br($product['attribute_value1']);
            }
            for ($i = 2; $i < 9; $i++) {
                if (!empty($product['attribute_value' . $i])) {
                    $product['_attr'][$product['attribute_label' . $i]] = nl2br($product['attribute_value' . $i]);
                }
            }

            $agegroup = $kvcobj->get('agegroup');
            if (!$agegroup) {
                $agegroup = $this->Lookup->getLookup('agegroup'); //年齡段
                $kvcobj->set('agegroup', $agegroup);
            }
            $body_skin = $kvcobj->get('body_skin');
            if (!$body_skin) {
                $body_skin = $this->Lookup->getLookup('body_skin'); //膚質
                $kvcobj->set('body_skin', $body_skin);
            }
            $product_reports_well = $kvcobj->get('product_reports_well');
            if (!$product_reports_well) {
                $product_reports_well = $this->Lookup->getLookup('product_reports_well'); //滿意度  很好、好
                $kvcobj->set('product_reports_well', $product_reports_well);
            }

            $vote_option_data = $product['vote_option_data']; //好評  美白度
            if (!empty($vote_option_data['result'])) {
                foreach ($vote_option_data['result'] as $k => $v) {
                    $vote_option_data['result'][$k]['score_v'] = !empty($product_report_res['category_score' . ($k + 1)]) ? $product_report_res['category_score' . ($k + 1)] : 1;
                }
            }

            $product['my_report_endtime'] = $mem_app['result']['report_endtime'];

            $arr5_10 = array();
            for ($i = 1; $i <= $product['max_pic_num']; $i++) {
                $arr5_10[] = $i;
            }
            $arr5 = array(1, 2, 3, 4, 5);
            $mtxt = $mtype == 5 ? '體驗' : '試用';
            $_isover = (time() > strtotime($mem_app['result']['report_endtime']) + 7 * 24 * 3600) ? 1 : 0;
            $product['report_endtime'] = $mem_app['result']['report_endtime'];
            $this->tmpl_assign('isover', $_isover);
            $this->tmpl_assign('show_draft_bt', (($product_report_res['is_publish'] == 0) ? 1 : 0));
            $this->tmpl_assign('mtxt', $mtxt);
            $this->tmpl_assign('arr5', $arr5);
            $this->tmpl_assign('arr5_10', $arr5_10);
            $this->tmpl_assign('selfurl', $this->selfurl);
            $this->tmpl_assign('pid', $pid);
            $this->tmpl_assign('rid', $rid);
            $this->tmpl_assign('mtype', $mtype);
            $this->tmpl_assign('product', $product);
            $this->tmpl_assign('toURL', $toURL);
            $this->tmpl_assign('agegroup', $agegroup);
            $this->tmpl_assign('body_skin', $body_skin);
            $this->tmpl_assign('product_reports_well', $product_reports_well);
            $this->tmpl_assign('vote_option_data', $vote_option_data);
            $this->tmpl_assign('product_report_res', $product_report_res);
            $pageValue['title'] = !empty($product['type_name']) ? $product['type_name'] . " - " : "";
            $pageValue['title'] .=!empty($product['cname']) ? $product['cname'] . " - " : "";

            $this->tmpl_assign('pageValue', $pageValue);
            return $this->load_tmpl("p_report_edit.php");
        }
    }

    function action_clear() {
        $kvc = trim($this->get_q('kvc', ''));
        clear_kvcache($kvc);
    }

    function action_star() {
        $kvcobj = getCache('product_star_new', array('expire' => 5 * 60 * 60));

        //top報告
        $top_report_list = $kvcobj->get("top_report_list");
        if (!$top_report_list) {
            $top_reports = $this->StaruserReport->getList();
            $top_report_list = array();
            $i = 0;
            if (!empty($top_reports)) {
                foreach ($top_reports as $v) {
                    $top_report_list[$i] = $v;
                    $top_report_list[$i]['photo_l'] = imore_avatar($v['photo']);
                    $top_report_list[$i]['body'] = wordscut($v['body'], 100);
                    $top_report_list[$i]['title'] = wordscut($v['title'], 15);
                    if (!empty($v['content_json'])) {
                        $content_arr = json_decode($v['content_json'], true);
                        //取一張圖
                        foreach ($content_arr as $v1) {
                            if (!empty($v1['p'])) {
                                $top_report_list[$i]['_pic'] = PhotoResize($v1['p'], 249, 249,0);
                                break;
                            }
                        }
                    }
                    $i++;
                    if ($i >= 3)
                        break;
                }
            }
            $kvcobj->set("top_report_list", $top_report_list);
        }

        //他們在分享
        $new_share_reports1 = $kvcobj->get("new_share_reports1");
        if (!$new_share_reports1) {
            $new_share_reports1 = $this->ProductReports->getReportsList(0, 0, 0, "TB1.addtime desc", 1, 4, 1, '', 0, 0, 2, 0, 1, 1);
            if (!empty($new_share_reports1['result'])) {
                foreach ($new_share_reports1['result'] as $k => $v) {
                    $new_share_reports1['result'][$k]['photo_l'] = imore_avatar($v['photo']);
                    $new_share_reports1['result'][$k]['body'] = wordscut($v['body'], 70);
                    if (!empty($v['content_json'])) {
                        $content_arr = json_decode($v['content_json'], true);
                        $ii = 1;
                        foreach ($content_arr as $v1) {
                            if (!empty($v1['p'])) {
                                $new_share_reports1['result'][$k]['_content'][$ii]['p1'] = PhotoResize($v1['p'], 152, 96,0);
                                $ii++;
                            }
                        }
                    }
                    $agegroup_list = $this->Lookup->getLookup('agegroup');
                    $new_share_reports1['result'][$k]['age_group'] = $agegroup_list['result'][intval($v['agegroup']) - 1]['cname'];
                    $user = $this->ModelMember->getMember($v['mid']);
                    $new_share_reports1['result'][$k]['user_type'] = $user['result'][0]['member_type'];
                }
            }
            $kvcobj->set("new_share_reports1", $new_share_reports1);
        }
        $new_share_reports5 = $kvcobj->get("new_share_reports5");
        if (!$new_share_reports5) {
            $new_share_reports5 = $this->ProductReports->getReportsList(0, 0, 0, "TB1.addtime desc", 1, 4, 1, '', 0, 0, 2, 0, 1, 5);
            if (!empty($new_share_reports5['result'])) {
                foreach ($new_share_reports5['result'] as $k => $v) {
                    $new_share_reports5['result'][$k]['photo_l'] = imore_avatar($v['photo']);
                    $new_share_reports5['result'][$k]['body'] = wordscut($v['body'], 70);
                    if (!empty($v['content_json'])) {
                        $content_arr = json_decode($v['content_json'], true);
                        $ii = 1;
                        foreach ($content_arr as $v1) {
                            if (!empty($v1['p'])) {
                                $new_share_reports5['result'][$k]['_content'][$ii]['p1'] = PhotoResize($v1['p'], 152, 96,0);
                                $ii++;
                            }
                        }
                    }
                    $agegroup_list = $this->Lookup->getLookup('agegroup');
                    $new_share_reports5['result'][$k]['age_group'] = $agegroup_list['result'][intval($v['agegroup']) - 1]['cname'];
                }
            }
            $kvcobj->set("new_share_reports5", $new_share_reports5);
        }

        /**
          //星級達人cms list
          $userlist_cms = $kvcobj->get("userlist_cms");
          if (!$userlist_cms) {
          $userlist_cms = $this->StaruserUser->getList();
          if (!empty($userlist_cms)) {
          $i = 1;
          foreach ($userlist_cms as $k => $v) {
          $userlist_cms[$k]['uid'] = $k;
          $userlist_cms[$k]['photo_l'] = imore_avatar($v['photo']);
          $userlist_cms[$k]['list_i'] = $i;
          $i++;
          }
          }
          $kvcobj->set("userlist_cms", $userlist_cms);
          }
         * */
        /* $fg_hilite_user = $kvcobj->get("fg_hilite_user");
          if (!$fg_hilite_user) {
          $fg_hilite_user_temp = $this->FG->get_fg_hilite_user();
          if (!empty($fg_hilite_user_temp)) {
          foreach ($fg_hilite_user_temp as $k => $v) {
          $fg_hilite_user[$k] = $v;
          $fg_hilite_user[$k]['_img'] = PhotoResize($v['photo_image1'],88,88);
          }
          }
          $kvcobj->set("fg_hilite_user", $fg_hilite_user);
          } */

        //星級達人瀏覽量排行
        $exp_click_list = $kvcobj->get("exp_click_list");
        if (!$exp_click_list) {
            $exp_click_first = $this->StaruserHiliteuser->getList();
            $exp_click_list = array();
            $exp_click_first_mid = 0;
            if (!empty($exp_click_first)) {
                $exp_click_list[0] = $exp_click_first;
                $exp_click_first_mid = $exp_click_first['mid'];
                $exp_click_list[0]['photo_l'] = PhotoResize($exp_click_first['photo'], 178, 178);
            }
            $exp_click_ten = $this->ProductReports->getReportsList(0, 0, 0, "(TB1.click+TB1.click_base_num) desc", 1, 11, 1, '', 0, 0, 2, 5);
            if (!empty($exp_click_ten['result'])) {
                foreach ($exp_click_ten['result'] as $k => $v) {
                    if ($v['mid'] != $exp_click_first_mid) {
                        $exp_click_list[$k + 1] = $v;
                        $exp_click_list[$k + 1]['photo_l'] = imore_avatar($v['photo']);
                    }
                    if (count($exp_click_list) > 10)
                        break;
                }
            }
            $kvcobj->set("exp_click_list", $exp_click_list);
        }
        //試用專員瀏覽量排行
        $try_click_list = $kvcobj->get("try_click_list");
        if (!$try_click_list) {
            $try_click_list = array();
            $try_click_ten = $this->ProductReports->getReportsList(0, 0, 0, "(TB1.click+TB1.click_base_num) desc", 1, 5, 1, '', 0, 0, 2, 1);

            if (!empty($try_click_ten['result'])) {
                foreach ($try_click_ten['result'] as $k => $v) {
                    $try_click_list[$k] = $v;
                    $try_click_list[$k]['photo_l'] = imore_avatar($v['photo']);
                    $try_click_list[$k]['title'] = wordscut($v['title'], 15);
                }
            }
            $kvcobj->set("try_click_list", $try_click_list);
        }

        //itrial分排行
        $points_list = $kvcobj->get("points_list");
        if (!$points_list) {
            $points_list = db_query_hash("member_imore", array("field" => "id,photo,username,points", "order" => "points desc", "limit" => "5"));
            if (!empty($points_list['result'])) {
                foreach ($points_list['result'] as $k => $v) {
                    $points_list['result'][$k]['photo_l'] = imore_avatar($v['photo']);
                    $_report = db_query_one("product_reports", array("field" => "TB1.id,TB1.oid,TB1.title,TB2.member_type", "where" => "TB1.mid=" . $v['id'] . " and TB1.is_blog=0 and TB1.is_accept=1 and TB1.is_valid=1 and TB1.status=1 and TB1.is_publish=1", "order" => "TB1.addtime desc", "join" => "left join product", "on" => "TB1.oid=TB2.id"));
                    $points_list['result'][$k]['rid'] = $_report['result']['id'];
                    $points_list['result'][$k]['pid'] = $_report['result']['oid'];
                    $points_list['result'][$k]['title'] = $_report['result']['title'];
                    $points_list['result'][$k]['member_type'] = $_report['result']['member_type'];
                }
            }
            $kvcobj->set("points_list", $points_list);
        }
        //echo '<pre>' . var_export($try_click_list, 1) . '</pre>';
        //$this->tmpl_assign('fg_hilite_user', $fg_hilite_user);
        $this->tmpl_assign('top_report_list', $top_report_list);
        $this->tmpl_assign('new_share_reports1', $new_share_reports1);
        $this->tmpl_assign('new_share_reports5', $new_share_reports5);
        //$this->tmpl_assign('userlist_cms', $userlist_cms);
        $this->tmpl_assign('exp_click_list', $exp_click_list);
        $this->tmpl_assign('try_click_list', $try_click_list);
        $this->tmpl_assign('points_list', $points_list);
        return $this->load_tmpl("star.php");
    }

    function action_fg() {
        $pid = intval($this->get_q('pid', 0, 'int'));
        $rid = intval($this->get_q('rid', 0, 'int'));

        if (empty($pid) || (empty($rid))) {
            return showMsgCode('無效鏈接！', '/');
        }
        $kvcobj = getCache('product_fg', array('expire' => KVC_EXPIRE));
        $product = $kvcobj->get($pid . '_data');
        if (!$product) {
            $product = $this->Product->get_product_byid($pid);
            $product['is_report_add'] = time() <= strtotime($product['report_starttime']) ? 0 : 1;
            $product['_diff_day'] = ceil((strtotime($product['report_endtime']) - strtotime($product['report_starttime'])) / 86400);
            $product['_photo_url'] = PhotoResize($product['cover'], 158, 158);
            $product['_overall'] = !empty($product['product_reports_stat']['scores']) ? $product['product_reports_stat']['scores'] : 0;
            if (!empty($product['price'])) {
                $product['_attr']['價格'] = '$' . $product['price'];
            }
            if (!empty($product['attribute_value1'])) {
                $product['_attr']['實際容量'] = nl2br($product['attribute_value1']);
            }
            for ($i = 2; $i < 9; $i++) {
                if (!empty($product['attribute_value' . $i])) {
                    $product['_attr'][$product['attribute_label' . $i]] = nl2br($product['attribute_value' . $i]);
                }
            }
            if (!empty($product['about_url']) && !empty($product['about_txt'])) {
                $product['_attr']['相關資料'] = "<a target='_blank' href='" . $product['about_url'] . "' target>" . nl2br($product['about_txt']) . "</a>";
            }
            //if(!empty($product['body'])){ $product['_attr']['編輯短評'] = nl2br($product['body']);}

            $kvcobj->set($pid . '_data', $product);
        }
        if (time() < strtotime($product['apply_starttime'])) {
            return showMsgCode('活動時間有誤！', '/');
        }
        $mtype = $product['member_type'];

        $product_fg_one = db_query_one('fg_product', array('field' => 'topicurl', 'where' => 'pid=' . $pid));

        $h_param = $reports_list_res = $fb_pic_array = array();
        $h_param['id'] = $rid;
        $reports_list_res = $kvcobj->get($pid . '_reports_list_res');
        if (!$reports_list_res) {
            $reports_list_res = $this->FG->get_fg_report($h_param);
            $global_url = $this->param('URL');
            if (!empty($reports_list_res['result'][0])) {
                //$_json = !empty($reports_list_res['result'][0]['vote_option_json']) ? $reports_list_res['result'][0]['vote_option_json'] :'';
                //$reports_list_res['result'][0]['vote_option'] = json_decode($_json, 1);

                $fb_result = file_get_contents("http://graph.facebook.com/" . $global_url . substr(optimize_url('product', 'fg', 'mtype=' . $mtype . '&pid=' . $pid . '&rid=' . $rid), 1));
                $fb_array = json_decode($fb_result, 1);
                $reports_list_res['result'][0]['fb_count'] = $fb_array['shares'] + $reports_list_res['result'][0]['fb_share_num_base'];
                $reports_list_res['result'][0]['share_url'] = optimize_url('product', 'fg', 'mtype=' . $mtype . '&pid=' . $pid . '&rid=' . $rid);
                $reports_list_res['result'][0]['title'] = str_replace(array("\r\n", "\n", "\r"), "", wordscut($reports_list_res['result'][0]['msg'], 20));


                $img_array = array();
                $fb_pic_array[0] = array('property' => 'og:image', 'content' => $global_url . PhotoResize($product['_photo_url'], 100, 100));
                preg_match_all('/<img.*?src=\"\/(.*?\.jpg)\".*?>/i', $reports_list_res['result'][0]['msg'], $img_array, PREG_PATTERN_ORDER);
                $img_array = array_unique($img_array[1]);
                if (!empty($img_array)) {
                    foreach ($img_array as $k1 => $v1) {
                        $reports_list_res['result'][0]['pic'][$k1] = PhotoResize($v1, 163, 102);
                        $fb_pic_array[] = array('property' => 'og:image', 'content' => $global_url . $reports_list_res['result'][0]['pic'][$k1]);
                        if ($k1 >= 2)
                            break;
                    }
                }
            }
            $kvcobj->set($pid . '_reports_list_res', $reports_list_res);
        }

        $pageoptions = array();
        $fb_other_array = array(
            array('property' => 'og:description', 'content' => htmlencode($reports_list_res['result'][0]['msg'])),
            array('property' => 'og:url', 'content' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']),
            array('property' => 'og:title', 'content' => htmlencode($reports_list_res['result'][0]['title'])),
        );

        $pageoptions['metas'] = array_merge($fb_pic_array, $fb_other_array);
        $meta = $this->meta;
        if ($meta) {
            foreach ($meta as $k => $v) {
                $meta[$k] = str_replace(array('[report]', '[product]'), array($product['cname'], $product['type_name'] . $product['cname']), $v);
            }
        }
        $this->tmpl_assign('meta', $meta);
        $this->tmpl_assign('product_fg_one', $product_fg_one);
        $this->tmpl_assign('pid', $pid);
        $this->tmpl_assign('rid', $rid);
        $this->tmpl_assign('mtype', $mtype);
        $this->tmpl_assign('product', $product);
        $this->tmpl_assign('reports_list_res', $reports_list_res['result'][0]);
        $this->tmpl_assign('memberData', $this->member);
        $this->tmpl_assign('SUPERUSER', SUPERUSER);

        $pageoptions['csses'][0] = "jquery.lightbox-0.5";
        $pageoptions['jses'][0] = "jquery.lightbox-0.5.min";
        $pageoptions['csses'][1] = "fg";
        $this->tmpl_assign('pageoptions', $pageoptions);

        $this->tmpl_assign('thisUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        $this->tmpl_assign('DetailUrl', urlencode('http://' . $_SERVER['HTTP_HOST'] . optimize_url('product', 'detail', 'mtype=' . $mtype . '&pid=' . $pid)));
        return $this->load_tmpl('p_fg.php');
    }

}

$webapp = new Product();
$webapp->run();
?>